【问题标题】:How to get value from Future in flutterFlutter中如何从Future中获取价值
【发布时间】:2022-10-24 18:36:59
【问题描述】:

我正在尝试制作一个货币转换器应用程序。

我计划的过程是..

  1. 在initState,从API获取当前货币数据
  2. 获取货币数据并将其分配给“currentCur”
  3. 使用“currentCur”计算转换后的货币值并显示该值

    但是,我收到一个错误,因为“currentCur”是“Future<dynamic”的实例,所以它无法计算,因为它不是“num”的子类型

    我怎样才能从 initState 中的 Future 获得价值?

    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());
      }
    

【问题讨论】:

  • 不应该是 currentCur = await fetchData();

标签: flutter dart


【解决方案1】:
  • 指定函数将返回一个值“未来”关键词
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()
  }

【讨论】:

猜你喜欢
  • 2020-01-22
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 2019-07-01
  • 2021-07-22
  • 2021-04-08
  • 2014-05-29
相关资源
最近更新 更多