我想定期将数据从main.dart
文件传递到当前可见的屏幕。我想在项目中使用哪个 flutter 组件?
最佳答案
您需要使用Stream.periodic功能和Provider软件包。下面是一个简单的例子:
创建一个business logic component
class Bloc {
/// Stream controller
final _streamController = StreamController<Object>.broadcast();
/// Object sink (send objects here)
void sink(Object value) => _streamController.add(value);
/// Object stream (listenable for objects)
Stream<Object> get stream => _streamController.stream;
void dispose() {
_streamController.close();
}
}
这是一个
main page
包装器(即应用程序):class MyApp extends StatelessWidget {
final bloc = Bloc()
MyApp() {
// Send object to stream each minute
Stream.periodic(Duration(minutes: 1), (count) {
bloc.sink(count);
});
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Some App',
theme: hemeData(
primarySwatch: Colors.blue,
),
// Provide `Bloc` object for `MainScreen` widget and its children
home: Provider<Bloc>(
create: (_) => bloc, // already created bloc
dispose: (_, bloc) => bloc.dispose(), // bloc will be disposed automatically
child: MainScreen(),
),
);
}
}
这是一个
MainScreen
:class MainScreen extends StatefulWidget {
/// Bloc to use in this screen
Bloc bloc;
@override
void initState() {
super.initState();
// Take `bloc` from widget tree (it is provided via `Provider` above
bloc = Provider.of<Bloc>(context);
// Subscribe for listening of objects
bloc.stream.listen((object) {
// Do some action when object received
print('$object');
});
}
@override
Widget build(BuildContext context) {
return Container();
}
}