Home > OS >  How to create a widget to work with the API?
How to create a widget to work with the API?

Time:05-09

I have the logic of working with the API in the same file with the body for the data it receives. How can I put the Future function, which takes the data into a separate file, correctly? My Future code:

//fetch data from API
  Future<List<CurrencyModel>?> _fetchCurrency() async {
    currencyList = [];
    final response = await http.get(
      Uri.parse(
          'https:...'),
    );
    if (response.statusCode == 200) {
      List<dynamic> values = [];
      values = json.decode(response.body);
      if (values.isNotEmpty) {
        for (int i = 0; i < values.length; i  ) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            currencyList.add(
              CurrencyModel.fromJson(map),
            );
          }
        }
        setState(() {
          currencyList;
        });
      }
      return currencyList;
    } else {
      throw Exception('Failed to load currencies');
    }
  }

CodePudding user response:

you can use future builder in all different widget

  • Related