0

I am trying to convert the response from api to string in flutter. I am still a beginner to Flutter so I'm sorry about that. Whenever I do the get and assign it to a variable, the value is always 'Instance of Future' rather than the actual text? So does this mean I have to convert it to text? This is the code that I used.

gethttps() async{
  var response = await http.get(url);

  print("JSON" + response.body);

  String data = response.body;
  data = json.decode(response.body.toString());
  return data;
}

CALL FROM OUTSIDE THE FUNCTION

var response = gethttps();

CSXZ
  • 19
  • 2

3 Answers3

1

you can follow the link : https://stackoverflow.com/a/50296350/6413387

Basically you have two options

gethttps().then((result) {
  print(result);
  setState(() {
    someVal = result;
  })
})

or

funcThatMakesAsyncCall() async {
  String result = await gethttps();
  print(result);  
  setState(() {
    someVal = result;
  })
}
towhid
  • 1,899
  • 4
  • 13
  • 24
0

You can change signature of function to this one

Future<String> gethttps() async{....}

and then use

var data=await gethttps();

user await

Shojaeddin
  • 1,458
  • 1
  • 13
  • 14
0

In order to get value out of the Future you have to use then method.

import 'dart:async';

gethttps() async{
  var response = await http.get(url);
  String data = response.body;
  data = json.decode(response.body.toString());
  return data;
}

Call function like this

gethttps().then((String result){
    var response = result;
});

.((value){…}) is a callback that’s called when future completes successfully(with a value).

Paresh Mangukiya
  • 37,512
  • 17
  • 201
  • 182
  • `ListView createArticleButtons() { gethttps().then((String result){ var response = result; }); print("The output is : $response");` Is this correct? @Paresh Mangukiya – CSXZ Dec 04 '20 at 17:22
  • You can do it this ways ListView createArticleButtons() { gethttps().then((String result) { var response = result; return ListView( padding: const EdgeInsets.all(8), children: [ Container( height: 50, color: Colors.amber[600], child: const Center(child: Text(response)), ), ], ); }); } – Paresh Mangukiya Dec 05 '20 at 03:26