Flutter-InheritedWidget-处理
问题内容:
我想知道是否有人知道何时处理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();
}
}
因此,主要问题是“ 如何调用BLoC的dispose()方法 ”?
非常感谢您的帮助。
问题答案:
InheritedWidget
行为与其他行为相同Widget
。他们的寿命很短:通常不超过一个build
电话。
如果您想存储更长的数据,那InheritedWidget
不是您想要的。您需要一个State
。
这也意味着,最终,您可以将State
的dispose用于您的bloc处置。
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() {
}
}