【发布时间】:2020-03-04 13:58:15
【问题描述】:
我目前正在编写一个 Flutter 应用程序。我有一个类 AdvancedAppBar,它扩展了 AppBar 并用作大多数屏幕的通用 AppBar。它是一个单独的文件。 AdvancedAppBar 有一个 FlatButton 和一个 PopUpMenu 作为子项。通过按下这些按钮,我想导航到另一个屏幕。 目前,我使用 Navigator 类在屏幕之间导航,但据我所知,这假定了一个 BuildContext,我不知道如何或是否有可能为 AppBar 定义一个 BuildContext。
如何实现这种导航?
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue
),
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/notifications': (context) => NotificationScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AdvancedAppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new MaterialButton(
height: 40.0,
minWidth: 300.0,
color: Colors.blue,
textColor: Colors.white,
child: new Text("Nachrichten", textScaleFactor: 2.0,),
onPressed: (){
Navigator.pushNamed(context, '/notifications');
},
)
],
),
),
);
}
}
class AdvancedAppBar extends AppBar{
AdvancedAppBar({Key key}) : super(
key: key,
title:
Container(child: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: FlatButton(
onPressed: () {
// here I would like to navigate to another screen
},
padding: EdgeInsets.all(0.0),
child: Image.asset('assets/images/Logo.png')
)
)
),
actions: <Widget>[
PopupMenuButton<PopUpStates>(
onSelected: (PopUpStates result) {
switch (result) {
case PopUpStates.settings: {
// here I would like to navigate to another screen
}
break;
case PopUpStates.logout: {
// here I would like to navigate to another screen
}
break;
default:
}},
itemBuilder: (BuildContext context) => <PopupMenuEntry<PopUpStates>>[
const PopupMenuItem<PopUpStates>(
value: PopUpStates.settings,
child: Text('Einstellungen'),
),
const PopupMenuItem<PopUpStates>(
value: PopUpStates.logout,
child: Text('Ausloggen'),
),
],
)
],
automaticallyImplyLeading: false
);
}
【问题讨论】:
-
请出示您的代码