简体   繁体   中英

How to dispose bloc when using Inherited Widget?

I have made a simple app using bloc and InheritedWidget . Following is the code

class Bloc {

  final StreamController<bool> _changeColor = PublishSubject<bool>();

  Function(bool) get changeColour => _changeColor.sink.add;

  Stream<bool> get colour => _changeColor.stream;

  void dispose(){
    _changeColor.close();
  }

}


class Provider extends InheritedWidget {

  final bloc = Bloc();
  Provider({Key key,Widget child}): super(key: key,child: child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }

  static Bloc of(BuildContext context){
    return (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;
  }


void dispose(){
    bloc?.dispose();
  }
}


class _HomePageState extends State<HomePage> {

  var bloc;

  @override
  void initState() {
    super.initState();
    bloc = Provider.of(context);
  }

  @override
  Widget build(BuildContext context) {

    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            bloc.changeColour(true);
          },
          child: Text("Change colour"),
        ),
        StreamBuilder(
          builder: (context, snapshot) {

            var bool = snapshot?.data ?? false;

            return Text(
              "First text",
              style:
              TextStyle(color: bool ? Colors.red : Colors.green),
            );
          },
          stream: bloc?.colour,
        ),
      ],
    );
  }


  @override
  void dispose() {
    super.dispose();
  }

}

I don't understand how to call dispose method of the bloc when using InheritedWidget . Of course I can create a global variable of bloc and avoid using InheritedWidget to dispose the bloc using the dispose method which is present in the bloc but I really want to use InheritedWidget .

Does using the PublishSubject from rxdart disposes the streamcontroller automatically, is it life cycle aware, I couldn't find anything related to this in the documentation. Is there any debugging process to make sure the streamcontroller is disposed off correctly?

That is not possible using Inheritedwidget . The widget is not made to handle data, but to share it.

You have to wrap your Inheritedwidget into a StatefulWidget and use the dispose of the latter

To add to Remi's answer, the code would look something like this

import 'package:flutter/material.dart';

abstract class BlocBase {
  void dispose();
}

class BlocProvider<T extends BlocBase> extends StatefulWidget {
  BlocProvider({
    Key key,
    @required this.child,
    @required this.bloc,
  }): super(key: key);

  final T bloc;
  final Widget child;

  @override
  _BlocProviderState<T> createState() => _BlocProviderState<T>();

  static T of<T extends BlocBase>(BuildContext context){
    final type = _typeOf<BlocProvider<T>>();
    BlocProvider<T> provider = context.ancestorWidgetOfExactType(type);
    return provider.bloc;
  }

  static Type _typeOf<T>() => T;
}

class _BlocProviderState<T> extends State<BlocProvider<BlocBase>>{

  @override
  void dispose(){
    widget.bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context){
    return widget.child;
  }
}

class Bloc implements BlocBase {

  final StreamController<bool> _changeColor = PublishSubject<bool>();

  Function(bool) get changeColour => _changeColor.sink.add;

  Stream<bool> get colour => _changeColor.stream;

  @override
  void dispose() {
    _changeColor.close();
  }

}


class _HomePageState extends State<HomePage> {
  Bloc bloc;
  var colour = false;

  @override
  void initState() {
    super.initState();
    bloc = BlocProvider.of<Bloc>(context);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            if (colour) {
              bloc.changeColour(false);
              colour = false;
            } else {
              bloc.changeColour(true);
              colour = true;
            }
          },
          child: Text("Change colour"),
        ),
        StreamBuilder(
          builder: (context, snapshot) {
            var bool = snapshot?.data ?? false;
            return Text(
              "First text",
              style: TextStyle(color: bool ? Colors.red : Colors.green),
            );
          },
          stream: bloc?.colour,
        ),
      ],
    );
  }

  @override
  void dispose() {
    print("Bloc is disposed");
    bloc.dispose();
    super.dispose();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM