用flutter+dart做一个底部导航栏包括:首页、购物车、订单、我的
时间: 2023-07-10 19:32:08 浏览: 175
Flutter实现底部导航栏
好的,以下是一个简单的底部导航栏的示例代码:
1. 在 pubspec.yaml 文件中添加依赖:
```
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
```
2. 在 lib 目录下创建四个页面,分别是 home.dart、cart.dart、order.dart 和 mine.dart。
3. 在 main.dart 文件中实现底部导航栏:
```
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'home.dart';
import 'cart.dart';
import 'order.dart';
import 'mine.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter BottomNavigationBar Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
static List<Widget> _widgetOptions = <Widget>[
Home(),
Cart(),
Order(),
Mine(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: CupertinoTabBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '首页',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
label: '购物车',
),
BottomNavigationBarItem(
icon: Icon(Icons.assignment),
label: '订单',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: '我的',
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
activeColor: Colors.blue,
inactiveColor: Colors.grey,
),
);
}
}
```
4. 在 home.dart、cart.dart、order.dart 和 mine.dart 文件中分别实现对应的页面,例如:
```
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text('首页'),
),
);
}
}
```
5. 运行程序,即可看到底部导航栏和对应的页面。
以上代码仅供参考,具体实现方式可以根据实际情况进行调整。
阅读全文