导航到新屏幕时,请保持底部导航栏



导航到新屏幕时,我想保留底部导航栏AppBar。当我返回页面时具有保存状态。

诀窍是使用"IndexedStack";在正文中,IndexedStack工作程序类似于StackWidget:

IndexedStack(
index: _selectedIndex,
children: _widgetOptions,
)

传递"children"中的小部件列表&"index"中小部件的索引。

以下是示例代码:

import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MyApp(),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BottomNavPage(),
);
}
}
class BottomNavPage extends StatefulWidget {
const BottomNavPage({Key? key}) : super(key: key);
@override
_BottomNavPageState createState() => _BottomNavPageState();
}
class _BottomNavPageState extends State<BottomNavPage> {
int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
NavHome(),
Text('Index 1: Business'),
Text('Index 2: School'),
Text('Index 3: Settings'),
];
Widget navHome() {
return Text(
'Index 0: Home',
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('BottomNavigationBar Sample')),
body: IndexedStack(
index: _selectedIndex,
children: _widgetOptions,
),
bottomNavigationBar: Material(
child: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
backgroundColor: Colors.blue,
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Home',
backgroundColor: Colors.blue,
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'Home',
backgroundColor: Colors.blue,
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Home',
backgroundColor: Colors.blue,
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.orange[400],
onTap: _onItemTapped,
),
),
);
}
}
class NavHome extends StatefulWidget {
const NavHome({
Key? key,
}) : super(key: key);
@override
_NavHomeState createState() => _NavHomeState();
}
class _NavHomeState extends State<NavHome> {
double _counter = 0;
void incrementCounter() {
setState(() {
_counter++;
});
}
void decrementCounter() {
setState(() {
_counter--;
});
}
@override
Widget build(BuildContext context) {
// Return a widget number in the center of the screen and button to increment the number
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text('Increment'),
onPressed: incrementCounter,
),
SizedBox(width: 10),
ElevatedButton(
child: Text('Decrement'),
onPressed: decrementCounter,
),
],
),
],
),
);
}
}

相关内容

  • 没有找到相关文章

最新更新