一 有状态和无状态
StatelessWidget 无状态的组件
StatefulWidget 有状态的组件,在生命周期内组件状态可以改变
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int countNumber = 1;
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(height: 200),
Text("$countNumber"),
SizedBox(height: 100),
ElevatedButton(
onPressed: () {
setState(() {
countNumber++;
});
print("$countNumber");
},
child: Text("change one second")),
],
);
}
}

二 自定义新增数据刷新列表
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List sourceData = [];
@override
Widget build(BuildContext context) {
return ListView(
children: [
Column(
children: sourceData.map((value) {
return Text(value);
}).toList(),
),
SizedBox(height: 20),
ElevatedButton(
child: Text("新增数据"),
onPressed: () {
setState(() {
sourceData.add("new add data");
});
},
)
],
);
}
}

三 自定义导航条
1 基本结构
BottomNavigationBar是Scaffold脚手架中的位于底部的一个组件,底部导航栏
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue,
selectedItemColor: Colors.red,
unselectedItemColor: Colors.grey,
currentIndex: currentIdx,
// 默认传入的索引值
onTap: (index) {
setState(() {
currentIdx = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home_filled), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), label: "购物车"),
BottomNavigationBarItem(icon: Icon(Icons.book), label: "我的")
]),
2 页面的跳转
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'Category.dart';
import 'Home.dart';
import 'ShopCart.dart';
import 'Profile.dart';
class Tabs extends StatefulWidget {
const Tabs({super.key, required this.title});
final String title;
@override
State<Tabs> createState() => _TabState();
}
class _TabState extends State<Tabs> {
int currentIdx = 0;
List pages = [MyHomePage(), CategoryPage(), ShopCartPage(), ProfilePage()];
@override
Widget build(BuildContext context) {
// 选中的索引值
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: pages[this.currentIdx],
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue,
selectedItemColor: Colors.red,
unselectedItemColor: Colors.grey,
currentIndex: currentIdx,
// 默认传入的索引值
onTap: (index) {
setState(() {
currentIdx = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home_filled), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), label: "购物车"),
BottomNavigationBarItem(icon: Icon(Icons.book), label: "我的")
]),
);
}
}
