//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
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.