I think I have a simple question but I don't know why its not work
Simple: main.dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const Welcome(),
);
}
}
Second file: welcome.dart
class Welcome extends StatelessWidget {
const Welcome({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
appBar: AppBarNav(
title: 'JobFinder',
),
);
}
}
AppBar file: appbar.dart
import 'package:flutter/material.dart';
class AppBarNav extends StatelessWidget {
final String title;
const AppBarNav({super.key, required this.title});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
);
}
}
Debbuger say: The argument type 'AppBarNav' can't be assigned to the parameter type 'PreferredSizeWidget?'
Why?
Do you know why the debugger tells me that I can't use AppBar in the Welcome.dart file? I know it's probably simple but I can't find a solution to it.
Generally I want to place an appBar on every screen (same Appbar)
Try this,
class AppBarNav extends StatelessWidget implements PreferredSizeWidget {
final String title;
const AppBarNav({super.key, required this.title});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
);
}
@override
// TODO: implement preferredSize
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
By implementing the PreferredSizeWidget
interface, you provide information to the framework about how much vertical space your widget should occupy in the app bar, allowing for proper layout and positioning of other widgets within the app bar.
In AppBarNav
, implemented the PreferredSizeWidget
interface because we want to customize the app bar's behavior, specifically its preferred size.
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
, is a getter method that defines the preferred size of a widget.
Size get preferredSize:
This line defines a getter method named preferredSize
that returns a Size
object.
Size.fromHeight(kToolbarHeight)
: This part creates a Size
object with the height specified by kToolbarHeight
. kToolbarHeight
is typically a constant defined in Flutter (often set to 56.0 in logical pixels), representing the standard height of a toolbar or app bar in a Flutter app.