我目前正在检查Flutter Provider软件包。我只想向小部件公开一些流,以便可以收听它们。像这样:
class OtherBloc {
BehaviorSubject<String> sub = new BehaviorSubject();
OtherBloc() {
sub.add('my value');
}
add(String value) {
sub.add(value);
}
}
然后像这样使用它
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final OtherBloc otherBloc = Provider.of<OtherBloc>(context);
return Scaffold(
body: new Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
StreamBuilder<Object>(
stream: otherBloc.sub,
builder: (context, snapshot) {
return Text(snapshot.data);
}
),
RaisedButton(
child: Text('____'),
onPressed: () => {
otherBloc.add('lol')
},
)
],
),
),
),
);
}
}
所以我会这样提供
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<OtherBloc>.value(
value: OtherBloc(),
child: MaterialApp(home: CounterPage()),
);
}
}
现在我的BehaivorSubject
从来没有close()
。我该如何调用派发类型的钩子,以便可以从一个团体中关闭流?
答案 0 :(得分:0)
我不知道您使用的是哪个提供商, 您可以使用此Provider的dispose属性。
您的情况将是:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<OtherBloc>.value(
builder: (context) => OtherBloc(),
dispose: (_, otherBloc) => otherBloc.dispose(),
child: MaterialApp(home: CounterPage()),
);
}
}