Сделайте ваш метод типа Future
и позвольте ему возвращать тип данных dynamic
следующим образом. А затем вызывайте его, где хотите.
Future<dynamic> fetchData() async {
final res = await http.get("https://jsonplaceholder.typicode.com/posts");
if (res.statusCode == 200) {
// If the call to the server was successful, parse the JSON
print("it works");
return json.decode(res.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
И вызывайте его через это, поскольку вы возвращаете данные
child: RaisedButton(
onPressed: () {
// the value is the call back function data which you're returning
fetchData().then((value){
// since the data it return is a dynamic one
print(value.toString());
});
}
)
Если вы не хотите возвращать какие-либо данные, и просто вызовите метод. Затем сделайте это
fetchData() async {
final res = await http.get("https://jsonplaceholder.typicode.com/posts");
if (res.statusCode == 200) {
// If the call to the server was successful, parse the JSON
print("it works");
// do not return
print(json.decode(res.body).toString());
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
И просто вызовите, как ваш вызов метода в вашем коде
child: RaisedButton(
// no need of anything now
onPressed: () => fetchData()
)