首页 > 解决方案 > 从 Flutter 中的 BottomNavigationBar-sceeen 导航到子屏幕

问题描述

我目前正在开发我的第一个简单的颤振应用程序,并试图找出我们处理屏幕之间导航的最佳方法。

已经可能:

问题:

代码示例:

我想要三个主屏幕Screen1()Screen2()并且Screen3()可以从BottomNavigationBar. 有Screen1()一个按钮可以导航到另一个屏幕,我们称之为Screen4(),用户可以在其中从项目列表中进行选择。然后,您可以将所有选择的项目添加到列表并导航回Screen1()

为了实现这一点,我创建了下面的代码。的主要Widgetbody根据所选的当前索引进行更改BottomNavigationItem

主要.dart


import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  static const String _title = 'Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _selectedIndex = 0;

  static const List<Widget> _widgetOptions = <Widget>[
    Screen1(),
    Screen2(),
    Screen3(),
  ];

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Stackoverflow Example'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Screen1'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Screen2'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('Screen3'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

问题是当我在Screen1()- 小部件中导航时Screen4()使用

Navigator.push(context,MaterialPageRoute(builder: (context) => Screen4()),);

导航将发生在外部,MyApp()因此没有Scaffold.

如果有人有一个例子,我会很高兴。感谢您的阅读。

标签: androidflutterflutter-navigation

解决方案


我知道这有点晚了,但希望它可以帮助你。

要实现这一点,您可以使用带有导航器的 Offstage 小部件作为其子级,这样您将在所有页面中都有一个持久的导航栏。

您可以按照本文了解更多详细信息以及如何实现它

https://medium.com/coding-with-flutter/flutter-case-study-multiple-navigators-with-bottomnavigationbar-90eb6caa6dbf

您可能需要稍微调整一下以匹配您的情况。

关于 Offstage 小部件的信息:

https://api.flutter.dev/flutter/widgets/Offstage-class.html


推荐阅读