无法使用 FutureBuilder 调用从 SharedPreferences 获取列表数据

Cannot get List data from SharedPreferences using FutureBuilder call

我的共享首选项中有一个字符串列表,用于存储帐号,然后可用于从 API:

拨打电话
List<String> accountList = [];

Future _getListData() async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
for(var i = 0; i < myPrefs.getStringList('accounts').length; i++){
  accountList.add(myPrefs.getStringList('accounts')[i]);
}
//prints values from shared preferences
print(accountList);
}

Future<List<dynamic>> fetchData() async {
_getListData();
//prints an empty list
print(accountList);
try {
  if (accountList == null) {
    var result = await http.get(apiUrl);
    List<dynamic> accountInfo = (json.decode(result.body));
    return accountInfo;
  } else {
    List<dynamic> accountInfo = [];
    for(var i = 0; i < accountList.length; i++){
      var result =
      await http.get(apiUrl + "/api/Data/GetCustomer?accntnum=" + accountList[i]);
      accountInfo.add(json.decode(result.body));
    }
    return accountInfo;
  }
} catch (e) {
  print(e);
}
}

当在小部件中从我的 FutureBuilder 调用 Future 函数“fetchData()”时,它 returns 一个空列表。但是,在“_getListData()”函数的范围内,它会打印具有适当值的列表。我怎样才能使“fetchData()”获得预期的列表?

只需在此处 _getListData() 之前添加一个等待:

Future<List<dynamic>> fetchData() async {
await _getListData();
//prints an empty list
print(accountList);