我想知道是否有人知道如何知道 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 dispose。
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() {
}
}
https://stackoverflow.com/questions/51690230/
相关文章:
dart - 在 Flutter 中显示全屏图像 onTap
google-maps - Flutter:如何使用新的 Marker API 向 Google M
dart - Flutter - 通过滑动或按下 floatingActionButton 来展开
flutter - 如何在 Flutter 的文本输入字段中配置自动大写行为?
android - 如何在文本小部件 flutter 中显示 html 字符串
dart - 如何更改手机屏幕上的 flutter 应用程序名称显示?
dart - 如何在 Flutter 中保存图像文件?使用 Image_picker 插件选择的文件