Home > Net >  NotifyListeners in Provider Pattern in MVC S Design
NotifyListeners in Provider Pattern in MVC S Design

Time:11-29

I m developing a Flutter APP in MVC S Design. Also I use the Providers with Notifylisteners but often I got the Message setState() or markNeedsBuild() called during build.

What is the Best practice of using Providers and Notfylisteners to avoid this problem ?

My Code looks like:

Class Test() {

String? testA
String? testB


FunctionA async() {
... 
testA = 'TestA';
notfifyListeners() };



FunctionB async() {
... 
testB = 'TestB';
notfifyListeners();

}

class Test extends StatefulWidget {
.
.
. 
class TestState extends State<Test> {
 @override
 voide iniState() {
  locator<TestController>().FunctionA();
  locator<TestController>().FunctionB();
  super.initState();
 }

}

.
.
.

}

CodePudding user response:

You need waiting for build was completed:

@override
void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      locator<TestController>().FunctionA();
      locator<TestController>().FunctionB();
    });
}

CodePudding user response:

Do not call provider in initState as at this moment your builder is still in the progress and there is no BuildContext available,

to avoid this many coders use Future Delay with mounted to check if BuildContext is ready or not in initState.

But FutureBuilder widget is the right option when you deal with future data. this will automatically build the widget when data is available you do not need to check for mounted.

CodePudding user response:

the reason you're getting the exception is that you're updating the state when the widget is attempting to build.

The easiest way to avoid this is using addPostFrameCallback to ensure the state is updated after the initial build(it's very important):

class TestState extends State<Test> {
 @override
 voide iniState() {
   WidgetsBinding.instance?.addPostFrameCallback((timeStamp){
      locator<TestController>().FunctionA();
      locator<TestController>().FunctionB();
    });
  super.initState();
 }

}

be careful to use addPostFrameCallback in your dispose method when you want to use a function that has notfifyListeners().

Happy coding....

  • Related