For separate appbar widget its must to add implements PreferredSizeWidget in class. Issue is that I see everyone uses it will StateLess Widget.
But I have a Stateful widget and wants to use it with that. How to add implement methods on Stateful widgets
When I add implements PreferredSizeWidget it gives error
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
@override
_MyAppBarState createState() => _MyAppBarState();
}
How can I fix it?
To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data. Inside the second page, access the variable using the widget. For example widget.
If you want to create your own custom prefered size widget all you need to do is to implement PreferredSizeWidget interface in your widget. Example: import 'package:flutter/material. dart'; class MyWidget extends StatelessWidget implements PreferredSizeWidget { @override Size get preferredSize => Size.
To create a stateful widget in a flutter, use the createState() method. The stateful widget is the widget that describes part of a user interface by building a constellation of other widgets that represent a user interface more concretely. A stateful Widget means a widget that has a mutable state.
A stateful widget is implemented by two classes: a subclass of StatefulWidget and a subclass of State . The state class contains the widget's mutable state and the widget's build() method. When the widget's state changes, the state object calls setState() , telling the framework to redraw the widget.
For anybody having the same problem, this is what I did
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
@override
_MyAppBarState createState() => _MyAppBarState();
// you can replace 100 to whatever value you wish to use
@override
Size get preferredSize => new Size.fromHeight(100);
}
class _MyAppBarState extends State<MyAppBar> {
@override
Widget build(BuildContext context) {}
}
You can use PreferredSize
for that, Like
Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(yourAppBarHeight),
child:Container(child: Text("Body of your app bar")
)
)
If you want to separate your app bar implementation and your code the other answer is more suitable for you.
Override preferredSize method and return Size using any constructor.
@override
Size get preferredSize => Size.fromHeight(50);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With