stackunderflow
stackunderflow

Reputation: 1794

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

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();
}

Upvotes: 0

Views: 231

Answers (3)

Dineth Prabashwara
Dineth Prabashwara

Reputation: 504

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") );
    }
}

Upvotes: 1

gouresh ghadi
gouresh ghadi

Reputation: 141

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();
}

Upvotes: 1

Alex Verbitski
Alex Verbitski

Reputation: 609

Try appBar: TopBar() as PreferredSizeWidget

Upvotes: 1

Related Questions