如何创建一个小部件以使用 API?

How to create a widget to work with the API?

我的逻辑是在同一个文件中使用 API 和接收数据的正文。如何正确放置将数据放入单独文件的 Future 函数? 我的未来代码:

//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');
    }
  }

您可以在所有不同的小部件中使用未来的构建器