Search code examples
flutterroutesflutter-futurebuilderflutter-go-router

navigation inside Futurebuilder


I am trying to navigate after login inside futurebuilder. api request done successfully but navigation getting error while testing. Help me How to use futurebuilder properly.

child: ElevatedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false otherwise.
                  if (_mobileKey.currentState!.validate()) {
                    FutureBuilder<Loginuser>(
                      future: loginuser(mobileController.text.toString(),
                          passwordController.text.toString()),
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          context.go('/Home');
                          return Text(snapshot.data!.message);
                        } else if (snapshot.hasError) {
                          return Text('${snapshot.error}');
                        }

                        // By default, show a loading spinner.
                        return const CircularProgressIndicator();
                      },
                    );
                  }

                  context.go('/Home');
                },
                child: const Text('Submit')),

I tried this its not working. I am using " go_router: ^5.2.4 " for navigation


Solution

  • Try removing the FutureBuilder from inside the ElevatedButton instead use Promises i.e then/catch to navigate to new screen

    Updated code:

    child ElevatedButton(
            child: Container(),
            onPressed: () async {
               // Remove the future builder from here
              await loginuser(mobileController.text.toString(),
                      passwordController.text.toString())
                  .then((result) {       
                     context.go('/Home');             // 👈 add your navigatin inside then block 
                  }).onError((error, stackTrace) {
                print(error);
              });