}
可以试着让widget从服务器加载这个数字:
class _CounterText extends StatefulWidget {
const _CounterText({Key key}) : super(key: key);
@override
__CounterTextState createState() => __CounterTextState();
}
class __CounterTextState extends State<_CounterText> {
@override
void initState() {
// 在initState中发出请求
_fetchData();
super.initState();
}
// 在数据加载之前,显示0
int count = 0;
// 加载数据,模拟一个异步,请求后刷新
Future _fetchData() async {
await Future.delayed(Duration(seconds: 1));
setState(() {
count = 10;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(‘$count’),
);
}
}
又或者,我们想让这个数字每秒都减1,最小到0。那么只需要把他变成stateful后,在initState中初始化一个timer,让数字减小:
class _CounterText extends StatefulWidget {
final int initCount;
const _CounterText({Key key, this.initCount:10}) : super(key: key);
@override
__CounterTextState createState() => __CounterTextState();
}
class __CounterTextState extends State<_CounterText> {
Timer _timer;
int count = 0;
@override
void initState() {
count = widget.initCount;
_timer = Timer.periodic(
Duration(seconds: 1),
(timer) {
if (count > 0) {
setState(() {
count–;
});
}
},
);
super.initState();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(‘${widget.initCount}’),
);
}
}
这样我们就能看到这个widget
从输入的数字每秒减少1。
由此可见,widget
可以在state
中改变数据,这样我们在使用StatefulWidget
时,只需要给其初始数据,widget
会根据生命周期加载或改变数据。
在这里,我建议的用法是在Scaffold
中加载数据,每个页面都由一个Stateful
的Scaffold
和若干StatelessWidget
组成,由Scaffold
的State
管理所有数据,再刷新即可。
注意,即使这个页面的body是ListView
,也不推荐ListView
管理自己的state
,在当前state
维护数据的list
即可。使用ListView.builder
构建列表即可避免更新数组时,在页面上刷新列表的全部元素,保持高性能刷新。