我正在开发底部导航栏,但我无法完美地按回按到主屏幕。
如果我从底部导航栏视图项目中选择两个以上导航按钮,那么当我按后退按钮时,它将关闭应用程序。
我想在按下后退按钮时返回主页。
这是我的代码。
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
后退按钮的默认行为是关闭您在顶部弹出的路由。在这种情况下,您还没有弹出新路线。您刚刚在新索引处显示了一个小部件。所以没有什么可以关闭的。
您可以通过以下选项返回后退按钮:
在
BottomNavigationBar
点击时,使用 Navigator.of(context).push(...)
显示新路线。然后后退按钮将关闭它。但使用这种方法,每个底部导航上都会出现新屏幕,从而使您的应用程序变得混乱,并且这些屏幕不会保留状态。
使用
WillPopScope
小部件拦截后退按钮事件并执行自定义操作,如下所示:https://stackoverflow.com/a/44637374/11382675但是使用这种方法,您必须手动将导航堆栈保留在某处。当您添加新屏幕时,这将变得不可扩展。
但我认为真正的问题是导航设计本身。现在每个选项卡都保留自己的导航历史记录已成为一种习惯。因此,当您来回切换选项卡时,每个选项卡仍然允许您独立于其他选项卡的历史记录返回自己的历史记录。
要实现此目标,第一步是确定不应通过后退按钮撤消切换选项卡。后面的步骤可以在这里找到:https://medium.com/flutter-community/flutter-navigation-maintaining-tab-state-while-navigating-bottomnavigationbar-6009fbceb59c
上面的答案是正确的,但
WillPopScope
已被弃用,但我们可以使用 Popscope
的 WillPopScope
实例。
return Scaffold(
body: PopScope(
canPop: true,
onPopInvoked: (didPop) {
Navigator.pop(context);
},
),
);
true
这意味着您可以在 onPopInvoked 方法下移动,之后我们可以在这里处理我们的逻辑。我们可以举出例子
显示警报对话框,或退出页面或导航到另一个页面。fales
它不会使用该功能,这意味着后退按钮被禁用。弹出按钮将允许我们到达后退按钮,那么底部导航底部的其余部分呢? ???