(更新自2024年6月)Flutter3中BottomNavigationBar的用法。
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return const MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int currentIndex = 0; void onTap(int index) { setState(() { currentIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Selected index: $currentIndex'), ), bottomNavigationBar: BottomNavigationBar( currentIndex: currentIndex, onTap: onTap, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.email), label: 'Email'), BottomNavigationBarItem( icon: Icon(Icons.settings), label: 'Settings'), ], ), ); } }
BottomNavigationBar 是 Flutter 的 Material 库的一部分,因此不需要添加额外的依赖。只需导入 material.dart 即可使用