Provider
作者:互联网
共享数据类的写法:
示例:
class Bloc {
final StreamController<String> _streamController = StreamController();
Stream<String> stream;
Bloc() {
stream = _streamController.stream.asBroadcastStream();
}
void dispose() {
_streamController.close();
}
}
在构造方法里面写赋值语句,在类里面写变量声明。可以声明数据流。
记得要dispose。
如果引用provider的话,一定要把方法里面的builder和dispose属性补齐;就这么写就可以了;
Provider<Bloc>(
builder: (_) => Bloc(),
dispose: (_, value) => value.dispose(),
child: Example(),
);
引用Provider数据:
Provider.of<Bloc>(context)._streamController.add('caolegequde');
这个里面的<Bloc>不可以忽略掉。
完整示例:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class Bloc {
final StreamController<String> _streamController = StreamController();
Stream<String> stream;
Bloc() {
stream = _streamController.stream.asBroadcastStream();
}
void dispose() {
_streamController.close();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<Bloc>(
builder: (_) => Bloc(),
dispose: (_, value) => value.dispose(),
child: Example(),
);
}
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.send),
onPressed: (){
Provider.of<Bloc>(context)._streamController.add('caolegequde');
},
),
appBar: AppBar(title: Text('ProviderDemo'),),
body: StreamBuilder<String>(
stream: Provider.of<Bloc>(context).stream,
builder: (context, snapshot) {
return Text(snapshot.data?.toString() ?? 'dashazinigeerhuo');
},
),
),
);
}
}
标签:stream,streamController,dispose,Bloc,context,Provider 来源: https://www.cnblogs.com/braveheart007/p/10837557.html