在Android中,每个Fragment都有重写onCreateOptionsMenu的功能,这为每个Fragment添加单独的选项菜单提供了可能性。在Flutter中,当应用栏是通用的时,如何在从抽屉中更改页面时实现此功能呢?
Flutter的优点在于您不必编写大量像HTML、CSS等属性,使用以下示例代码中提供的一种属性即可以简单的方式实现:
在Scaffold下,只需添加此代码:
appBar: AppBar(
title: Text("Action Demo"),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.settings,
color: Colors.white,
),
onPressed: () {
// do something
},
)
],
),
您可以在每个屏幕上添加AppBar。
class SDF extends StatefulWidget {
@override
_SDFState createState() => _SDFState();
}
class _SDFState extends State<SDF> {
int body = 0;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("I Am AppBar"),
actions: getActions(body),
),
body: getBody(body), //here you can add your body
drawer: Drawer(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
setState(() {
body = 0;
});
},
child: Text("Home"),
),
RaisedButton(
onPressed: () {
setState(() {
body = 1;
});
},
child: Text("Settings"),
),
],
),
),
);
}
getBody(int body) {
switch (body) {
case 0:
return Container(); // Home Screen
case 1:
return Container(); // Settings Screen
}
}
getActions(int body) {
switch (body) {
case 0:
return [
Icon(Icons.settings),
Icon(Icons.home),
]; // Home Screen
case 1:
return [
Icon(Icons.home),
Icon(Icons.settings),
]; // Settings Screen
}
}
}
在构建AppBar
时,请添加actions
。在您的页面的State
对象中执行此操作,并使用该状态(还控制您的主体)来控制您的操作创建。例如,使用IconButton
列表:
// We're withing the PageState here. e.g.
// class MyPageState extends State<MyStateObject> {
Widget createAppBar() {
return AppBar(
actions: createAppBarActions()
);
}
List<Widget> createAppBarActions() {
// use your app state here to create the actions you need
// use if / else or switch / case for the states
return [
IconButton(
icon: Icon(Icons.share),
onPressed : onSharePressed,
),
];
}
void onSharePressed() {
// execute the action here
}
如果您使用上述的Icons
包,请不要忘记导入material
。
import 'package:flutter/material.dart';