Home > OS >  Flutter - Cannot set an appbar as a widget to the scaffold
Flutter - Cannot set an appbar as a widget to the scaffold

Time:06-03

I want to create a responsive appbar without need to setState to the entire scaffold when there are changes. The problem is I can set a BottomNavigationBar widget to the scaffold's bottomNavigationBar but I can't do the same with an AppBar to set to it's appBar. I get this error

The argument type 'TopBar' can't be assigned to the parameter type 'PreferredSizeWidget'

I've simplified the code with the States only part.

class StateLayoutNav extends State<LayoutNav>{

    @override
    Widget build(BuildContext context) => Scaffold(
        bottomNavigationBar : BottomBar(), appBar : TopBar()
    );
}

class StateTopBar extends State<TopBar>{

    @override
    Widget build(BuildContext context) => AppBar();
}

class StateBottomBar extends State<BottomBar>{

    @override
    Widget build(BuildContext context) => BottomNavigationBar();
}

CodePudding user response:

Try appBar: TopBar() as PreferredSizeWidget

CodePudding user response:

My solution would be implementing your Appbar widget with PreferredSizeWidget as Appbar need to be of preferredSize

class TopBar extends StatefulWidget with PreferredSizeWidget {
    TopBar({Key key}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);

    @override
    final Size preferredSize; 

    @override
    StateTopBar createState() => StateTopBar();
}

class StateTopBar extends State<TopBar>{

    @override
    Widget build(BuildContext context) => AppBar();
}

CodePudding user response:

Try this. It will give you a custom app bar with any customisable widget. You can add fixed Container. Solution is implementing app bar with PreferredSizeWidget.

    class TopBar extends StatefulWidget implements PreferredSizeWidget {
    TopBar({Key? key}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);

    @override
    final Size preferredSize; // default is 56.0

    @override
    _TopBarState createState() => _TopBarState();
}

class _TopBarState extends State<TopBar>{

    @override
    Widget build(BuildContext context) {
        return Container( child: Text("Sample App Bar") );
    }
}
  • Related