如何在Flutter中添加Appbar操作

5
在Android中,每个Fragment都有重写onCreateOptionsMenu的功能,这为每个Fragment添加单独的选项菜单提供了可能性。在Flutter中,当应用栏是通用的时,如何在从抽屉中更改页面时实现此功能呢?

你想在每个Fragment上更改应用栏吗?还是想让它们都有相同的应用栏? - Muhammad Noman
我希望每个片段都有相同的应用程序栏,就像安卓一样。 - Karthick Ramanathan
如果您希望在每个屏幕上都有相同操作的应用栏 - 您可以创建抽象类,其中需要应用栏。并将此类扩展到所有屏幕。 - Andrii Turkovskyi
3个回答

8

Flutter的优点在于您不必编写大量像HTML、CSS等属性,使用以下示例代码中提供的一种属性即可以简单的方式实现:

在Scaffold下,只需添加此代码:

appBar: AppBar(
      title: Text("Action Demo"),
      actions: <Widget>[
        IconButton(
          icon: Icon(
            Icons.settings,
            color: Colors.white,
          ),
          onPressed: () {
            // do something
          },
        )
      ],
    ),

5

您可以在每个屏幕上添加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
    }
  }
}

是的,我也是这样做的,但我想知道是否还有其他像安卓一样的方法。 - Karthick Ramanathan
请简要说明您需要什么,我没有完全理解。 - Lakhwinder Singh
2
我们如何添加一个onPressed或onTaped函数,以便在操作按钮被轻触后前往另一页? - macleash

2

在构建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';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接