什么是Stream?
Flutter中Stream也是实现异步编程的一种方式。
Stream的字面意思是水流,Stream不像Future那样只会在未来获取一个值,它可以异步获取0个或者多个值。如果说Future是一个异步版本的int或者String,Stream则更像是异步版本的列表。
Stream一般结合StreamBuilder和StreamController 使用。
Stream<int> createStream() {
return Stream.periodic(Duration(seconds: 1), (i) => i);
}
void main() {
createStream().listen((data) {
// 处理数据流中的每个数据项
print(data);
});
}
import 'package:flutter/material.dart';
import 'dart:async'; // 需要导入异步包
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: DemoPage(),
);
}
}
class DemoPage extends StatefulWidget {
@override
State<DemoPage> createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
// 定义一个类型为int的Stream
final _controller = StreamController<int>();
@override
void dispose() {
super.dispose();
_controller.close();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Stream Demo"),
),
body: Wrap(
spacing: 20,
children: [
ElevatedButton(
// 按钮点击后Stream会释放出数字1
child: const Text("Emit 1"),
onPressed: () => _controller.add(1),
),
ElevatedButton(
// 按钮点击后Stream会释放出数字2
child: const Text("Emit 2"),
onPressed: () => _controller.add(2),
),
ElevatedButton(
// 按钮点击后Stream会释放出一个错误
child: const Text("Emit Error"),
onPressed: () => _controller.addError("oops"),
),
ElevatedButton(
// 按钮点击后Stream会关闭
child: const Text("Close"),
onPressed: () => _controller.close(),
),
StreamBuilder(
stream: _controller.stream ,
builder: (context, snapshot) {
print("正在重新绘制StreamBuilder组件…");
if (snapshot.connectionState == ConnectionState.done) {
return const Text("数据流已关闭");
}
if (snapshot.hasError) return Text("${snapshot.error}");
if (snapshot.hasData) return Text("${snapshot.data}");
return const Center(
child: CircularProgressIndicator(),
);
},
)
],
),
);
}
}
Dart Flutter入门实战项目教程网盘下载地址:http://bbs.itying.com/topic/620268d1a4bcc00fe8e9d6e1