Flutter 项目实战 底部导航 六
在Flutter中创建带有底部导航栏的应用程序,可以使用CupertinoTabBar
和CupertinoTabScaffold
来实现iOS风格的底部标签栏,或者使用BottomNavigationBar
和Scaffold
来实现更常见的Material Design风格。
以下是一个简单的例子,展示如何使用BottomNavigationBar
创建一个带有底部导航的Flutter应用程序:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Home',
style: optionStyle,
),
Text(
'Business',
style: optionStyle,
),
Text(
'School',
style: optionStyle,
),
Text(
'Health',
style: optionStyle,
),
Text(
'Govt',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
title: Text('School'),
),
BottomNavigationBarItem(
评论已关闭