0

i read about flutter hooks some weeks ago and wanted to implement it now in my new project. My kind of "base" widget is a stateful widget which has the mixin RouteAware cause of some project reasons. Furthermore each has a bloc which provides BehaviourSubject. The bloc has to be disposed by the Widget that's why and also cause of the RouteAware its a StatefulWidget. I don't get much into detail here but the bloc is build with many dependencies and is passed like this MyWidget(bloc: //resolve bloc here).

Can someone help me here to convert this to a HookWidget and how to add a useAware Hook?

class MyBloc{

 void dispose(){}

 void didPopNext(){}

 void didPush(){}


}

class MyWidget extends StatefulWidget{

  final MyBloc bloc;

  MyWidget({key, this.bloc}) : super(key: key);

  @override
  MyWidgetState createState() => MyWidgetState();


}


class MyWidgetState extends State<MyWidget> with RouteAware{

@override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context));
  }

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

  @override
  void didPush() {
    // Route was pushed onto navigator and is now topmost route.
    widget.bloc.didPush();
  }

  @override
  void didPopNext() {
    // Covering route was popped off the navigator.
    widget.bloc.didPopNext();
  }

  @override
  Widget build(BuildContext context) => StreamBuilder(stream: widget.bloc.myStream, initialValue: widget.bloc.myStream.value, builder: (context, snapshot){

//work with snapshot

});

} 
Yetispapa
  • 2,174
  • 2
  • 30
  • 52

1 Answers1

7

To call a dispose method using hooks you can use useEffect hook, where the return of the function is the method you want to use to dispose

useEffect((){   
   return bloc.dispose
}, const [])

Jose Georges
  • 883
  • 8
  • 16