Home > Back-end >  Flutter Difference between InitState and just putting inside Widget Build function
Flutter Difference between InitState and just putting inside Widget Build function

Time:10-24

I had an error every time I restarted my App: This widget has been unmounted, so the State no longer has a context (and should be considered defunct). and saw that something was not correct with my initstate. The initState was:

  @override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      BlocProvider.of<TutSkippedCubit>(context).load();
    });
    super.initState();
  }

the methods loads the data from sharedprefs if I have already skipped the tut or not. Now I solved this issue with removing the initState method and putting the function call inside the widget build:

  @override
  Widget build(BuildContext context) {

    BlocProvider.of<TutSkippedCubit>(context).load();
     ....

The widget build gets called when the pages loads, so, isn't it the same as the initial state? For what exactly is the methode initState() and I have the feeling that my way of handling this problem is a bad practise, but what would be a better way, how do I solve it?

CodePudding user response:

The initState() method is to control what happens after the app is built. The problem is that you call BlocProvider before the app begins. The correct way is to put all the actions after super.initState() call and add the context to the BlocProvider inside build method. Like this:

TutSkippedCubit? tutSkippedCubitProvider;

@override
void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      tutSkippedCubitProvider!.load();
    });
}

@override
Widget build(BuildContext context) {
    tutSkippedCubitProvider = BlocProvider.of<TutSkippedCubit>(context);
    ...
}

CodePudding user response:

The initState and build method is called when the widget is inserted into the widget tree, but the build method also is called every time the state is changed.

You do need to have in mind that every time the state is changed your method BlocProvider.of<TutSkippedCubit>(context).load(); also is called.

Maybe, the code below can help you:

 WidgetsBinding.instance.endOfFrame.then(
      (_) async {
        if (mounted) {
          BlocProvider.of<TutSkippedCubit>(context).load();
        }
      },
    );

CodePudding user response:

You wouldn't be surprise of getting that error since you are using BlocProvider.<T>(context) out of a BuildContext. This context in bracket is the just the same as the one given in the build function.

The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree.

  • Related