【Flutter】底部导航BottomNavigationBar的使用
warning:
这篇文章距离上次修改已过314天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'主页',
style: optionStyle,
),
Text(
'消息',
style: optionStyle,
),
Text(
'百度',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('底部导航示例'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('主页')),
BottomNavigationBarItem(icon: Icon(Icons.message), title: Text('消息')),
BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('搜索')),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
这段代码实现了一个带有底部导航栏的简单应用,用户可以通过底部导航栏切换不同的页面。每个页面都是一个简单的Text
控件,展示对应的标题。当用户点击底部导航栏中的不同项时,通过_onItemTapped
方法更新当前选中的索引,并重新渲染页面内容。这是学习Flutter底部导航栏使用的一个很好的示例。
评论已关闭