I want to receive data from an API and for that I created a SERVICE:
class ApiService {
Future<List<dynamic>> getData() async {
try {
var response = await http.get(Uri.parse(Config.apiURL));
debugPrint('Response code: ${response.statusCode}');
if (response.statusCode == 200) {
List<dynamic> data=jsonDecode(response.body) as List<dynamic>;
debugPrint('in service:${data.toString()}');
return data ;
}
else{
debugPrint('else');
return [];
}
} catch (e) {
throw Exception("Failed to fetch data..");
}
}
}
And I called him from StatefulWidget
:
void getData() async {
debugPrint('entrance');
userDataList= await ApiService().getData();
debugPrint(userDataList.toString());
}
@override
void initState() {
debugPrint('init');
super.initState();
getData();
}
And for some reason I am not receiving data.Would love your help.
2
Answers
Check the Flutter devtool network inspector to see what is the response of your request. Also check that your device can well reach internet : no dns issue, proxy, vpn errors.
If your method is call and never respond, maybe check the version of http used ? Old one ?
To help you, i need more :
You can do this in more than one way, two of them can be:
1) using setState in the Future
2) using StreamBuilder
remembering that you are dealing with a streamController, so consider the dispose()
ApiService class: