0
//sign() fnction is in statless widget 
var y
y=signIn(); 
 Navigator.of(context).push(
                         MaterialPageRoute(
                           builder: (context) =>  posting(y),
                         ),
                       );

Future<Response?> signIn() async {
  var dio = Dio();
  try {
    var response = await dio.post('https://cisfapp.cisf.gov.in/abc/post.php',
        data: {
          "method"  : "posting",
          "username" : 1652356789
        },
        options: Options(
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
        ));
    Map mapResponse = {};
    mapResponse = jsonDecode(response.data);
    var x = mapResponse['data'][2]['unit_name'];
    print(x); //want to pass the value of x to next page 

    return response;
  } catch (e) {
    print(e.toString());
  }
  return null;
}

this is the output of above program which is properly working according to me

please check in image,it is showing Instance of 'Future<Response<dynamic>?>

api output is :- { "message":"success", "err-code":"0", "data": [ { "unit_name":"alpha", "from_date":"2010-04-01 00:00:00", "sector_name":"TRG" }, { "unit_name":"Bravo", "from_date":"2018-03-10 00:00:00", "sector_name":"Eastern" }, { "unit_name":"charlie", "from_date":"2020-05-09 00:00:00", "sector_name":"western" } ]

} i want the specific value of unit_name which is "charlie" and which is at index [2] of output api......help pls if anyone can

3 Answers3

1

Use await keyword for wait for response from API.

    var y
    y.then(result => {
       Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => posting(result),),);
      }).catch(error => {
    });


Future<String?> signIn() async {
    var dio = Dio();
    try {
      var response = await dio.post('https://cisfapp.cisf.gov.in/abc/post.php',
          data: {
            "method" : "posting",
            "username" : 1652356789
          },
          options: Options(
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
              }
          ));
      Map mapResponse = response.data as Map<dynamic, dynamic>;
      return mapResponse['data'][2]['unit_name'];
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
Ravi Patel
  • 89
  • 4
  • please look at api result { "message":"success", "err-code":"0", "data": [ { "unit_name":"alpha", "from_date":"2017-04-01 00:00:00", "sector_name":"TRGan" }, { "unit_name":"baravo", "from_date":"2018-03-10 00:00:00", "sector_name":"East" }, { "unit_name":"charlie", "from_date":"2022-05-09 00:00:00", "sector_name":"Eastern" }]} – suman singh Apr 11 '23 at 09:50
  • above is the api result and i want the value of unit_name at [2] index which is charlie......your code helped but it gave the overall output of api but i want a specific result...please rply soon – suman singh Apr 11 '23 at 09:51
  • this shows console like this type 'String' is not a subtype of type 'Map' – suman singh Apr 12 '23 at 04:18
  • Map mapResponse = response.data as Map; try this and let me know @sumansingh – Ravi Patel Apr 12 '23 at 05:24
  • E/flutter (28370): #0 Element._debugCheckStateIsActiveForAncestorLookup. (package:flutter/src/widgets/framework.dart:4334:9) E/flutter (28370): #1 Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:4348:6) E/flutter (28370): #2 Element.findAncestorStateOfType (package:flutter/src/widgets/framework.dart:4415:12) E/flutter (28370): #3 Navigator.of (package:flutter/src/widgets/navigator.dart:2602:40) E/flutter (28370): #4 login_page.build.. (package:flogin.dart – suman singh Apr 13 '23 at 09:49
1

The error may be because signIn() returns a Future<String?> but you are trying to pass the result of the future (which is a String?) to the posting constructor. Instead, you should wait for the future to complete and then pass the result to the constructor. You can do this using the await keyword. Here's an example:

var response = await signIn(); // wait for signIn() to complete and get the response
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => posting(response), // pass the response data to the constructor
  ),
);

  Future<String?> signIn() async {
var dio = Dio();
try {
  var response = await dio.post('https://cisfapp.cisf.gov.in/abc/post.php',
      data: {"method": "posting", "username": 1652356789},
      options: Options(headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }));
  Map mapResponse = {};
  mapResponse = jsonDecode(response.data);
  var x = mapResponse['data'][2]['unit_name'];
  return x;
} catch (e) {
  print(e.toString());
}
return null;

}

Also, make sure that you are handling errors properly. If there is an error while fetching data from the API, signIn() will return null. You should handle this case and show an appropriate error message to the user.

Sartaj Roshan
  • 204
  • 2
  • 6
  • ur answer helped but it gave the overall result of api but i want the value of index [2] of data which u can see in the above code of my. – suman singh Apr 11 '23 at 09:54
  • please look at api result { "message":"success", "err-code":"0", "data": [ { "unit_name":"alpha", "from_date":"2017-04-01 00:00:00", "sector_name":"TRGan" }, { "unit_name":"baravo", "from_date":"2018-03-10 00:00:00", "sector_name":"East" }, { "unit_name":"charlie", "from_date":"2022-05-09 00:00:00", "sector_name":"Eastern" }]} – suman singh Apr 11 '23 at 09:54
  • @sumansingh, You will get it (mapResponse['data'][2]['unit_name']) from signIn() right? – Sartaj Roshan Apr 12 '23 at 11:32
  • by doing acording to code i got overall result of api but as you replied i want the value of mapResponse['data'][2]['unit_name'] to travell to next page – suman singh Apr 13 '23 at 09:33
  • Also added signIn function to the answer. Please check. – Sartaj Roshan Apr 14 '23 at 06:14
  • thankq sartaj Roshan it worked... – suman singh May 01 '23 at 05:32
  • dear sartaj roshan thank you for help.....but i have more question if i want to access the value of mapResponse['data'] than what should i do .....please rply soon – suman singh May 02 '23 at 07:14
  • Return complete mapResponse data from signIn function. – Sartaj Roshan May 02 '23 at 07:48
  • if i return x,which consist of mapResponse['data'] than it gives error like 'List' is not a subtype of type 'FutureOr' what should i do – suman singh May 02 '23 at 11:05
0

You can try this, or simply using await

var y;
y = signIn();
y.then(result => {
    Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) => posting(result),),);

}).catch(error => {
});
FoxVSky
  • 124
  • 5
  • thanks sir,but i want the specific value of x.as the api result consist of too many data , but i want only the value of unit_name field – suman singh Apr 11 '23 at 09:42