我想知道是否有人知道何时处理一个InheritedWidget?
这个问题的原因是我正在做一些实验,我使用的是InheritedWidget作为BLoC的提供者.此BLoC在InheritedWidget级别初始化,并使用StreamController.
由于建议关闭StreamController,我试图找到一个解决方案.
这是一段代码(仅用于实验的愚蠢代码)来说明问题:
///
/// ApplicationProvider
///
/// A provider of ApplicationBloc
///
class ApplicationProvider extends InheritedWidget {
//
// Initialization of the BLoC
//
final ApplicationBloc bloc = new ApplicationBloc();
ApplicationProvider({Key key, Widget child}) : super(key: key, child: child);
@override
bool updateShouldNotify(_) => true;
static ApplicationBloc of(BuildContext context, [bool redraw = true]) {
return redraw ? (context.inheritFromWidgetOfExactType(ApplicationProvider) as ApplicationProvider).bloc
: (context.ancestorWidgetOfExactType(ApplicationProvider) as ApplicationProvider).bloc;
}
}
//
// The BLoC
//
class ApplicationBloc {
int _counter;
StreamController<int> _counterController = new StreamController<int>.broadcast();
Sink get inCounter => _counterController;
Stream<int> get outCounter => _counterController.stream;
ApplicationBloc(){
_counter = 0;
}
void increment(){
_counter++;
inCounter.add(_counter);
}
int get counter => _counter;
//
// How could I call this method ???
//
void dispose(){
_counterController.close();
}
}
Run Code Online (Sandbox Code Playgroud)
所以主要的问题是" 如何调用我的BLoC的dispose()方法 "?
非常感谢您的帮助.
Rém*_*let 13
InheritedWidget行为与其他行为相同Widget.他们的生命非常短暂:通常不会超过一次build通话.
如果您想将数据存储更长时间,InheritedWidget则不是您想要的.你需要一个State.
这也意味着最终,你可以使用State处理你的集团处置.
class BlocHolder extends StatefulWidget {
final Widget child;
BlocHolder({this.child});
@override
_BlocHolderState createState() => _BlocHolderState();
}
class _BlocHolderState extends State<BlocHolder> {
final _bloc = new MyBloc();
@override
Widget build(BuildContext context) {
return MyInherited(bloc: _bloc, child: widget.child,);
}
@override
void dispose() {
_bloc.dispose();
super.dispose();
}
}
class MyInherited extends InheritedWidget {
final MyBloc bloc;
MyInherited({this.bloc, Widget child}): super(child: child);
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
return oldWidget != this;
}
}
class MyBloc {
void dispose() {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6196 次 |
| 最近记录: |