在我的Flutter应用程序中,我想定义自定义AppBar个动作.必须在子小部件中定义该操作单击时调用的方法(在我的情况下是Page1Page2),因为在这些小部件中有Bloc个提供者等,因此不可能在Home小部件中直接定义方法.

我将Home个小部件定义如下:

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _selectedIndex = 0;

  static final List<Widget> _options = <Widget>[
    const Center(child: Page1()),
    const Center(child: Page2()),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(""),
        actions: [
        ],
      ),
      body: IndexedStack(index: _selectedIndex, children: _options),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(label: "P1", icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: "P2", icon: Icon(Icons.home)),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        onTap: _onItemTapped,
      ),
    );
  }
}

有什么方法可以做到这一点吗?我try 用Provider来执行,但这种方式不适合,因为有IndexedStack(因此当我在构建方法中调用AppBar更改时,它只被调用一次,而不是每次我进入该特定页面时).

推荐答案

您可以根据_selectedIndex设置AppBar个操作:

AppBar(
  title: Text(""),
    actions: [
      if(_selectedIndex == 0)
        IconButton(...),
      if(_selectedIndex == 1)
        IconButton(...),
    ],
),

要访问Page1Page2中的方法,您可以使用此处描述的GlobalKey https://medium.com/@paalu.heing/efficient-communication-between-parent-and-child-widgets-in-flutter-c551f8e5dbeb

通过这GlobalKey,您可以访问页面小部件的当前状态.然后您可以将您的IconButtons个方法中的onPressed个方法设置为您的子元素Page1Page2个方法:

final GlobalKey<Page1State> _page1Key = GlobalKey<Page1State>();
...
IconButton(
  onPressed: () => _page1Key.currentState?.onActionButtonPressed(),
)

Flutter相关问答推荐

无法将Flutter 连接到Firebase

从底部开始固定,然后使其可拖曳Flutter

Flutter 翼doctor 显示的错误,我似乎不能修复.问题:系统32、Android工具链、Windows 10 SDK

Flutter :在后台实现振动

在Flutter 小部件测试中找不到框中的AssetImage装饰

摆动更改标记可轻敲文本按钮样式

dart /长笛中的返回早期模式和拆分方法

如何手动将 FirebaseAuth 用户邮箱验证状态设置为 true

如何在flutter中更改showModalBottomSheet小部件中CheckboxListTile小部件的值?

flutter Listview构建器溢出

如何获取flutter中gridview项目占用的高度和宽度?

'type' Icon '不是类型' IconData '的子类型

在 Flutter 中更改喜欢按钮的 colored颜色

无法使用 bloc 更新 ListView.builder 的特定时间

为什么 ref.watch(otherProvider.stream) 在 Riverpod 2.x 中被弃用并且将在 3.x 中被删除?

如何更改中心的圆形进度指示器

Flutter Serverpod 在示例项目上返回 400 错误

如何将 void 函数放入单独的 dart 文件的单独页面中

为什么这个循环只发生一次?Flutter /dart

FLUTTER+SQL:在 ListViewBuilder 中显示数据库中的数据