How to add add implements PreferredSizeWidget in stateful widget

Viewed 2320

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?

3 Answers

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);
Related