0

I'm trying to accomplish what I though would be simple before I started learning flutter.

const apiKey = 'xxxxxx';
const coinApiURL = 'https://rest.coinapi.io/v1/exchangerate';

class _CurrencyState extends State<CurrencyScreen> {

void getData() async {
http.Response response = await http.get('$coinApiURL/BTC/USD?apikey=$apiKey');

String data = response.body;
double exchangeRate = jsonDecode(data)['rate'];
print(exchangeRate);
}

@override
  Widget build(BuildContext context) {
    getData(); // prints out the value
    print(exchangeRate); // error "Undefined name 'exchangeRate'"
    (...)
    child: Text($exchangeRate) // value has to be inserted here
  }

So while I can use the function getData to print the data that it contains, I can't print out the 'exchangeRate' value. Therefore I too can't insert the value into the Text widget.

Can anyone explain me in a simple words how is that working and how I can get the value of 'exchangeRate' variable and use it in the code?

3
  • flutter.dev/docs/cookbook/networking/fetch-data Commented Sep 12, 2020 at 10:24
  • That doesn't really address my issue, but I updated my question so it's easier to understand what I'm trying to accomplish Commented Sep 12, 2020 at 11:00
  • you cannot do it that way, you have a Future coming from getData() method so you have to use FutureBuilder as in the link i posted Commented Sep 12, 2020 at 11:02

1 Answer 1

1

I changed your code so the Text widget is build after getData finish prosses http response data.

const apiKey = 'xxxxxx';
const coinApiURL = 'https://rest.coinapi.io/v1/exchangerate';

class _CurrencyState extends State<CurrencyScreen> {

// fetch http data and return rate value 
Future<double> getData() async {
http.Response response = await http.get('$coinApiURL/BTC/USD?apikey=$apiKey');
String data = response.body;
double exchangeRate = jsonDecode(data)['rate'];
print(exchangeRate);
// return exchangeRate value
return exchangeRate;
}

@override
  Widget build(BuildContext context) {
  return FutureBuilder<double>(
    // assign getData() to futureBuilder
    future: getData(),
    builder: (BuildContext  context, AsyncSnapshot<double> snapshot) {
      // handle getData error
      if (snapshot.hasError) {
        return Text('Error');
      }
      // handle success fetched data
      if (snapshot.hasData) {
        return Text(snapshot.data.toString());
      }
      // return progress indicator while loading data
      return Center(child: CircularProgressIndicator());
    },
     );
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.