FutureBuilder代码笔记
import 'package:flutter/material.dart';
class User {
String name;
int age;
User({this.name = 'lzh', this.age = 28});
@override
String toString() {
return name;
}
}
class FutureBuildWidget extends StatefulWidget {
const FutureBuildWidget({Key? key}) : super(key: key);
@override
_FutureBuildWidgetState createState() => _FutureBuildWidgetState();
}
class _FutureBuildWidgetState extends State<FutureBuildWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
// 设置子组件统一的文本样式
body: DefaultTextStyle(
style: TextStyle(fontSize: 40, color: Colors.blue),
child: Center(
child: FutureBuilder(
// 设置一个初始值
// initialData: 100,
// 模拟一个2秒的耗时操作
future: Future<User>.delayed(
Duration(seconds: 2),
() => User(),
),
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// 1、判断Future的状态是否完成
if (snapshot.hasData) {
return Text(
'${snapshot.data?.name} ${snapshot.data?.age}'); // 2、获取Future返回的数据
}
// 设置了初始值,就不会走loading了
return CircularProgressIndicator();
}),
),
),
);
}
}
StreamBuilder代码笔记
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class StreamBuildWidget extends StatefulWidget {
@override
_StreamBuildWidgetState createState() => _StreamBuildWidgetState();
}
class _StreamBuildWidgetState extends State<StreamBuildWidget> {
// 创建一个数据流
final StreamController _streamController = StreamController.broadcast();
// 创建一个Stream数据流
Stream<DateTime> getDateTimeStream() async* {
while (true) {
await Future.delayed(Duration(seconds: 1));
// 类似Python的yield
yield DateTime.now();
}
}
@override
void initState() {
super.initState();
// 多方监听需要设置为广播数据流
_streamController.stream.listen((event) {
print(event);
});
}
@override
void dispose() {
super.dispose();
// 页面销毁时,关闭数据流
_streamController.close();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
// 往数据流中放数据
onPressed: () => _streamController.sink.add(Random().nextInt(2)),
),
body: Center(
child: Container(
child: StreamBuilder(
// 监听自己创建的数据流
stream: _streamController.stream
.where((event) => event is int) // 筛选事件
.map((event) => event * 2) // 对事件进行封装
.distinct(), // 事件去重
// 事件没变的时候,build不会重新绘制
builder: (BuildContext context, AsyncSnapshot snapshot) {
print('build widget...');
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Text('waiting');
case ConnectionState.active:
// 初始有数据的时候的逻辑
if (snapshot.hasError) {
return Text('${snapshot.error}');
} else {
return Text('${snapshot.data}');
}
case ConnectionState.done:
return Text('done');
}
},
),
)),
);
}
}