探索 Flutter 中的 NavigationRail:使用详解
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'NavigationRail 示例',
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 _onSelectItem(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: _onSelectItem,
backgroundColor: Colors.blue[200],
labelType: NavigationRailLabelType.all,
selectedLabelTextStyle: TextStyle(fontSize: 12, color: Colors.black54),
unselectedLabelTextStyle: TextStyle(fontSize: 12, color: Colors.black26),
destinations: const <NavigationRailDestination>[
NavigationRailDestination(icon: Icon(Icons.home), label: Text('主页')),
NavigationRailDestination(icon: Icon(Icons.message), label: Text('消息')),
NavigationRailDestination(icon: Icon(Icons.people), label: Text('好友')),
],
),
);
}
}
这段代码演示了如何在Flutter应用中使用NavigationRail组件创建底部固定的导航栏。用户可以点击底部的导航按钮来切换当前视图。代码中包含了如何处理选项卡的点击事件,并更新对应的视图状态。这是一个简单的用于学习和实践的例子。
评论已关闭