0

I want to call method from another class which contains setState. I got some error in page 2like this

This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.

I've read this answer, but I didnt get it on my case. Any Ideas? Thank you

class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {

  @override
  void initState(){
    Page2().method();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
      ),
    );
  }
}
class Page2 extends StatefulWidget {
  method() => createState().methodInPage2();
  @override
  _Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
  Future<List<String>> methodInPage2() async{
    
//error here
    setState(){
      //setState here,
    }
  }
  @override
  Widget build(BuildContext context) => Container();
}
Soveyyy
  • 274
  • 4
  • 17
  • since Page2 class hasn't been inserted into the widget tree yet you can not use setState method. you can use ValueChanged callback that report that a value has been changes from page2. you can follow this example -> https://stackoverflow.com/questions/51798498/flutter-setstate-to-another-class – Nikunj Ramani Jul 06 '22 at 03:43
  • Calling `setState` before `initState` is called makes no sense. See the [`State` object lifecycle](https://api.flutter.dev/flutter/widgets/State-class.html). – jamesdlin Jul 06 '22 at 05:33

0 Answers0