didChangeDependencies hook in Flutter Widget includes not accurate data of the class

后端 未结 2 585
执念已碎
执念已碎 2021-01-28 13:10

In my code below, I am struggling with LifeCyrles in Flutter where I can update my State in Provider, APPARENTLY, only in didChangeDependencies hook or in a templat

相关标签:
2条回答
  • 2021-01-28 14:09

    I am new to flutter as well, But I have learned about a few architecture patterns that have helped me build some apps.

    Here is how I do it:

    Create a Provider which holds the data for you in runtime. (It can be a Bloc in your case). Stick to one architecture, don't try to put providers and blocs in the same project. Both are used for state management and only using one would be a great practice.

    Second, Register the providers using ChangeNotificationProvider or any other widgets which does a similar job of rebuilding the child widget when a data gets changed.

    Third, Get the provider in the build method of the widget that is supposed to change when the value of the variable provider changes. This way only the concerned widget is redrawn.

    For your case, If you want to hide the header and footer once you reach the last page, you can declare a variable, let's say isLastPage set to false by default in your provider. Next, wrap the widget, i.e. header and footer with ChangeNotificationListner

    Now, let that widget decide what it has to do based on the value of isLastPage, either hide itself or show.

    I hope this helps!

    0 讨论(0)
  • 2021-01-28 14:14

    At the long run, I seem to have found Mounted lifecycle hook in Flutter which is implemented with the help of Future.microtask. Unlike .addPostFrameCallback:

    SchedulerBinding.instance
            .addPostFrameCallback((_) => this._detectLastPage());
    

    Which is triggered only once like InitState (but only at the end of the build execution), Future.microtask can be placed inside build block and be invoked after every change and state update.

    It doesn't solve the problem with the inaccurate state in didChangeDependencies hook but provides another way to perform post-build executions.

    Credits for the current solution to @Abion47

    example

    Future.microtask(() => this._detectLastPage());
    
    0 讨论(0)
提交回复
热议问题