【发布时间】:2020-03-06 16:18:43
【问题描述】:
我目前正在开发我的第一个简单的颤振应用程序,并试图找出我们处理屏幕之间导航的最佳方法。
已经有可能:
- 使用
BottomNavigationBar+BottomNavigationBarItem浏览屏幕 - 使用
Navigator.push(context,MaterialPageRoute(builder: (context) => Screen4()),);导航
问题:
- 在
BottomNavigationBar的屏幕中有子屏幕
代码示例:
我想要三个主屏幕Screen1()、Screen2() 和Screen3() 可从BottomNavigationBar 访问。在Screen1() 中有一个按钮可以导航到另一个屏幕,我们称之为Screen4(),用户可以在其中从项目列表中进行选择。然后,您可以将所有选择的项目添加到列表中并导航回Screen1()。
为了实现这一点,我创建了以下代码。 body的主Widget会根据选中的BottomNavigationItem的当前索引而改变。
main.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() - Widget 中导航到 Screen4() 时使用
Navigator.push(context,MaterialPageRoute(builder: (context) => Screen4()),);
导航将发生在MyApp() 之外,因此没有Scaffold。
如果有人有一个例子,我会很高兴。 感谢您的阅读。
【问题讨论】:
标签: android flutter flutter-navigation