如何在infl中的initState中调用异步方法

时间:2020-04-03 15:16:57

标签: api flutter flutter-web flutter-state

我需要从端点获取一些信息。我有这种方法:

List<Widget> cardsList = List();
List<dynamic> cardsId = List();

addToList() async {
    var jsonData = await Provider.of<CardData>(context).cardsList;
    print(jsonData);
    for (var i = 0, len = jsonData.length; i < len; i++) {
      if (jsonData[i]['account_type'] == "1") {
        cardsList.add(
          BankCard(
            bankName: jsonData[i]['title'],
            colors: [Color(0xFFD00E00), Color(0xFFF44336)],
            cardNumber: jsonData[i]['number'],
            cardDesc: jsonData[i]['description'],
          ),
        );
        cardsId.add(jsonData[i]['id']);
      }
    }
  }

和称为CardData的提供程序数据类:

import 'package:flutter/material.dart';

import '../cards/cards.dart';

class CardData extends ChangeNotifier {
  static Cards cards = Cards();

  Future<dynamic> cardsList = cards.getCards();
}

和一个称为Card的类,用于发送请求并执行其他所有操作:

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class Cards {
  String _accessToken;
  String _refreshToken;

  Future<dynamic> getCards() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    _accessToken = sharedPreferences.getString("access");
    _refreshToken = sharedPreferences.getString("refresh");
    var jsonData;

    var response = await sendRequestToGetCards(
        url: "http://10.0.2.2:8000/accounts/list/", accessToken: _accessToken);
    if (response.statusCode == 200) {
      jsonData = json.decode(utf8.decode(response.bodyBytes));
      return jsonData;
    } else if (response.statusCode == 401) {
      _accessToken = await getNewAccessToken(_refreshToken);
      response = await sendRequestToGetCards(
          url: "http://10.0.2.2:8000/accounts/list/",
          accessToken: _accessToken);
      if (response.statusCode == 200) {
        jsonData = json.decode(utf8.decode(response.bodyBytes));
        return jsonData;
      }
    }
  }

  getNewAccessToken(String refreshToken) async {
    var refreshResponse = await http.post(
        "http://10.0.2.2:8000/users/api/token/refresh/",
        body: {'refresh': refreshToken});
    if (refreshResponse.statusCode == 200) {
      var jsonData = json.decode(refreshResponse.body);
      return jsonData['access'];
    }
  }

  sendRequestToGetCards({String url, String accessToken}) async {
    var response = await http.get(
      url,
      headers: {"Authorization": "Bearer $accessToken"},
    );
    return response;
  }
}

但是当我在 initState 中调用 addToList 方法以在build方法之前检索数据时,主UI消失了。

怎么了?

1 个答案:

答案 0 :(得分:0)

您可以在initState中调用异步函数,但由于它本身不是异步函数,因此在继续使用build方法之前,它不会等待future完成,这就是您的UI消失的原因,因为它正在构建而没有数据因此没有卡。我建议您在build方法中使用FutureBuilder来在异步函数返回时进行构建。