Home > Software design >  How can I call a function in a class that has the setState function from another stateful widget?
How can I call a function in a class that has the setState function from another stateful widget?

Time:09-04

I have a Stateful widget that uses the setState method in one of its class methods. I want to convert that widget into an ordinary class so I can use it in Object Oriented Programming. I want to instantiate an instance of that class in another stateful widget and access the methods that have the setState method in them. But I am currently getting this error "The method 'setState' isn't defined for the type 'MyClass'. Try correcting the name to the name of an existing method, or defining a method named 'setState'."

How can I do this?

CodePudding user response:

The setState method is linked to the state of a stateful Widget. If you want to convert your widget to a Class you can't use setState in it. But you can give the Class a Function as parameter. Anytime you instantiate this Class in a stateful Widget just give the setState from this stateful Widget to the class.

CodePudding user response:

I think you need to add a better state management solution to your code than stateful widget ,maybe riverpod, Using riverpod you can access the same notifier from other widgets and thus the setState functionality plus it has the added benefit of splitting the logic and ui into an mvvm like pattern

CodePudding user response:

SetState is only uses it for the stateful widget.you cannot call set state in the class without a stateful widget.So if you want to do that you can use statemangment in the flutter like Provider,Bloc or Getx.

  • Related