Reputation: 71
I made via a tutorial a own app bar with a gradient color. But now can I not navigate with the buttons to my settings view. The button needs a context. Can you help me how I fix this issue please? Thanks!
class MyAppBar extends AppBar {
MyAppBar({Key key, Widget title})
: super(
key: key,
title: title,
centerTitle: true,
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Color.fromRGBO(255, 120, 84, 1),
Color.fromRGBO(236, 10, 131, 1)
])
)),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.notifications),
onPressed: ()=> print("tap"),
),
new IconButton(
icon: new Icon(Icons.settings),
onPressed: () => Navigator.pushReplacementNamed(context, Settings.id),
)
]);
}
Upvotes: 0
Views: 1122
Reputation: 33
You can pass a new param to your MyAppBar({Key key, Widget title}) being the context: MyAppBar({Key key, Widget title, BuildContext context}) and then using it within MyAppBar. It does the work on my side when using Navigator.pushReplacementNamed(context, "some.path") You will have to add such param in MyAppBar class definition and make it required
Upvotes: 0
Reputation: 175
You need to extend a StatelessWidget to get your BuildContext and then implement PreferredSizeWidget because the AppBar itself implements it.
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final String screenTitle;
MyAppBar({@required this.screenTitle});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(screenTitle),
actions: // Whatever you need
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
You also need to override get preferredSize and specify a height. In this example, I used a constant already specified by Flutter that is 56.0 for the toolbar component of the AppBar.
Upvotes: 1