Flutter - InheritedWidget - dispose

boe*_*edi 6 flutter

我想知道是否有人知道何时处理一个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)

  • 为什么你不想使用`StatefulWidget`?它是Flutter的基本构建块之一,它没有任何问题. (3认同)
  • 析构函数不是问题.无论如何,你不应该在"InheritedWidget"中存储你的"BLOC"或类似的东西.您可以很容易地发现自己处于一种情况,即您的集团在没有任何明显原因的情况下进行硬重置 (2认同)