使用按钮在flutter应用中做到页面之间的跳转,一个简单的dmeo
直接上代码
这是lib/main.dart
import 'package:flutter/material.dart';
import './pages/tabs.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title:'Flutter demo',
theme: ThemeData(
primaryColor: Colors.blue
),
home: Tabs(),
);
}
}
然后是lib/pages/tabs.dart
使用了两个变量分别是一个currentindex记录当前tab的索引
一个page列表记录的是三个页面的组件
然后是ontap函数是一个点击事件的回调函数,参数就是tab的索引值
import 'package:flutter/material.dart';
import './tabs/home.dart';
import './tabs/category.dart';
import './tabs/settings.dart';
class Tabs extends StatefulWidget {
const Tabs({Key? key}) : super(key: key);
@override
State<Tabs> createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex=0;
List<Widget> _pages=[
HomePage(),
CategoryPage(),
SettingPage()
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter demo"),
),
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index){
setState(() {
_currentIndex=index;
});;
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: "首页",
),
BottomNavigationBarItem(
icon: Icon(Icons.people),
label: "好友",
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: "设置",
),
],
),
);
}
}
然后是三个按钮分别对应的页面:
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Center(
child:Text("首页")
);
}
}
import 'package:flutter/material.dart';
class CategoryPage extends StatefulWidget {
const CategoryPage({Key? key}) : super(key: key);
@override
State<CategoryPage> createState() => _CategoryPageState();
}
class _CategoryPageState extends State<CategoryPage> {
@override
Widget build(BuildContext context) {
return Center(
child: Text("category"),
);
}
}
import 'package:flutter/material.dart';
class SettingPage extends StatefulWidget {
const SettingPage({Key? key}) : super(key: key);
@override
State<SettingPage> createState() => _SettingPageState();
}
class _SettingPageState extends State<SettingPage> {
@override
Widget build(BuildContext context) {
return Center(
child: Text("设置"),
);
}
}
最后的效果就是:
刚开始在首页:
然后点击好友:
然后再点击设置:
。