0

I'm trying to make a currency converter app in flutter.

The process I've planned was..

  1. At the initState, get current currency data from API
  2. Get currency data and assign it to 'currentCur'
  3. Calculate converted currency value with 'currentCur' and display the value

But, I got an error that since 'currentCur' is Instance of 'Future<dynamic' so it can't calculated cause it is not subtype of 'num'

How can I get just value from Future in initState?

class _ConverterWidgetState extends State<ConverterWidget> {
  late final TextEditingController _current;
  late final currentCur;
  late final currency;

  fetchData() async {
    try {
      http.Response response = await http.get(
        Uri.parse(
          'https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD',
        ),
      );
      String jsonData = response.body;
      var basePrice = jsonDecode(jsonData)[0]['basePrice'];
      devtools.log(basePrice.toString());

      return basePrice;
    } catch (e) {
      devtools.log(e.toString());
    }
  }
  
  getCurrency(a) async {
    return await Future.value(a);
  }

  @override 
  void initState() {
    super.initState();
    _current = TextEditingController(text: 1000.toString());

    currentCur = fetchData();
    devtools.log(currentCur.toString());
  }
henni
  • 3
  • 3

1 Answers1

0
  • Specify the function is going to return a value with the "Future" keyWord
Future<num> fetchData() async {
var basePrice = 0;
    try {
      http.Response response = await http.get(
        Uri.parse(
          'https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD',
        ),
      );
      String jsonData = response.body;
      basePrice = jsonDecode(jsonData)[0]['basePrice'];
      devtools.log(basePrice.toString());

    } catch (e) {
      devtools.log(e.toString());
    }
      return basePrice;

  }

void updateCurrentCur ()async{
  var basePrice = await fetchData();
  setState(() {
    currentCur  = basePrice;
  });
}

  @override
  void initState()  {
    super.initState();
    updateCurrentCur()
  }

70B1 H4CK3R
  • 322
  • 1
  • 10
  • 1
    as far i know, you can't change `initState` in to `async` method. It will throw an error. https://stackoverflow.com/q/51901002/12838877 – pmatatias Oct 21 '22 at 07:47