1

In The below code, I am making a login screen, in which after doing an API call, so after getting the data I want to navigate to next screen, I am doing navigation from future builder but it's not working.

So, Please help.

    futureBuilder<Album>(
                        future: userFuture,
                        builder: (ctx, snapshot) {
                          if (snapshot.hasData) {
                            isApiCall = false;
                            print("hasDat");
                            if (snapshot.data.errorMsg == "") {
                              _showToast(snapshot.data.errorMsg);
                            } else {

// I added this part to navigate screen, but it did not works
                               Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
                              //_showToast(snapshot.data.errorMsg);
                              //return Home();
                              if(snapshot.connectionState == ConnectionState.waiting){
                                return CircularProgressIndicator();
                              }
                              else{

                                navigateToNextScreen=true;
                              }
                              Navigator.of(context).push(MaterialPageRoute(builder: (context) => Home()));
                              //return Text(snapshot.data.errorMsg);
                            }
                          } else if (snapshot.hasError) {

                          }

                          return CircularProgressIndicator();
                        },
                      )),

logic in button which triger API,s

onPressed: () {
                          setState(() {
                            isApiCall = true;

                            userFuture=_futureAlbum();
                            print(_futureAlbum);
                          });
                        },

Below are the future object inside statefull widget,

Future<Album> userFuture;

       @override
      void initState() {

        super.initState();
        userFuture=_futureAlbum();
      }

    Future<Album>_futureAlbum()async{
        if (isApiCall){
        return await createAlbum("http://api/login01", {
                                      'userPhoneNumber':
                                          "91" + controller.text.toString(),
                                      'userPassword':
                                          _passwordController.text.toString()
                                    });}
        else{
          return null;
        }

      }

Below are my API's call classes and method which are being called by above functions

class Album {
  final String errorMsg ;
  final Map success;

  Album({this.errorMsg, this.success});

  factory Album.fromJson(Map<String, dynamic> json) {
    if (json.containsKey("error")){
      print(json["error"]["errorMsg"]);
      print("sfsdfdsdfsfd");
      return Album(errorMsg:json["error"]["errorMsg"].toString());
    }

    else{return Album(success:json["success"]);}
  }
}
Future<Album> createAlbum(String url, Map reqBody) async {
      final Map success={};
      final Map errorMsg={};
      final Map res={};
      final http.Response response = await http.post(
        url,
        headers: <String, String>{
          'Content-Type': 'application/json',
        },
        body: jsonEncode(reqBody),
      );

      if (response.statusCode == 200) {
        print(response.body);
        Map<dynamic, dynamic>res = json.decode(response.body);
        return Album.fromJson(json.decode(response.body));
      } else {
        throw Exception('Failed to create album.');
      }
    }

1 Answers1

0

A good option would be to use the Memoization technique here. Memoization commonly used in functional programming and recursion, can be used to keep the values returned by a function in memory so that the function wouldn't have to run again. Other than this, the only option would be to not change pages and nest that entire widget inside the Futurebuilder itself.

revmatcher
  • 757
  • 8
  • 17