0

Using flutter 2.x and Get package version ^4.1.2.

i have a widget like so:

class InitializationScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future:
            // this is just for testing purposes
            Future.delayed(const Duration(seconds: 4)).then((value) => "done"),
        builder: (context, snapshot) {
          if (shouldProceed(snapshot)) {
            Get.toNamed("/login");
          }

          if (snapshot.hasError) {
            // handle error case ...
          }

          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }

  bool shouldProceed(AsyncSnapshot snapshot) =>
      snapshot.hasData && snapshot.connectionState == ConnectionState.done;
}

Get.toNamed("/login"); used inside FutureBuilder leads to this error:

The following assertion was thrown building FutureBuilder(dirty, state: _FutureBuilderState#b510d): setState() or markNeedsBuild() called during build.

  • I tried to check the connectionStatus (based on a SO answer) but it didn't work.

any help?

joe_inz
  • 998
  • 2
  • 13
  • 30

3 Answers3

0

build method is intended for rendering UI. You logic is not connected to rendering at all, so even without an error it doesn't make sense to put it into build method.

It's better to convert this method to StatefulWidget and put the logic in initState, e.g.:

Future.delayed(const Duration(seconds: 4))
  .then((value) => "done")
  .then((_) => Get.toNamed("/login"));
Kirill Bubochkin
  • 5,868
  • 2
  • 31
  • 50
  • Actually i don't want to move to another screen from `.then((_) => Get.toNamed("/login"))` that's the reason why i used `FutureBuilder`, so later on, i want to implement a function that checks for several things like the status of user is he logged in or not and based on that i'll redirect to the appropriate screen from the `FutureBuilder`. – joe_inz Apr 04 '21 at 17:40
  • If this function will be doing some rendering based on the value, there won't be an error. – Kirill Bubochkin Apr 04 '21 at 18:26
0

try this

  Future.delayed(Duration.zero, () async {
     your set state 
  
    });
0

This error happens when the setState() is called immediately during the screen's initial build(). In order to avoid this, you can do a work around by putting the setState() within a Future.delayed, something like:

Future.delayed(Duration(milliseconds: 100), () => Get.toNamed("/login"));
Bach
  • 2,928
  • 1
  • 6
  • 16