在flutter中同时获取数据

时间:2019-07-11 11:52:45

标签: api flutter dart

我需要对此进行澄清,我创建了一个包含asyn的sharepreferrence函数,并且在同一函数中尝试从服务器获取数据,并使用FutureBuilder显示输出  但是我观察到的是数据一直在同时获取,
这可能是什么问题。这是代码

我的数据获取功能

List<TransactionsModel> parseTransactons (String responseBody) {
  Map data = json.decode(responseBody);
  var output = data['transactions']; //returns a List of Maps
  final castingtoMAP =  output.cast<Map<String, dynamic>>();
  return castingtoMAP.map<TransactionsModel>((json) => 
    TransactionsModel.fromJson(json)).toList();
}

Future<List<TransactionsModel>> fetchTransactions(http.Client client)  async {
  final SharedPreferences prefs = await 
  SharedPreferences.getInstance();
  String email = prefs.getString('Email');
  String session = prefs.getString('session');

  var map = new Map<String, String>();
  map["email"] = email;
  map["sesscode"] = session;

  var response = await http.post(new API().Transaction, body: map);
  print('*********Response from Transaction API***** $response');
  return parseTransactons(response.body); 
} 

显示数据

FutureBuilder<List<TransactionsModel>>(
  future: fetchTransactions(http.Client()),
  builder: (context, snapshot) {
    if (snapshot.hasError)
       return MyFunctions().showToast(snapshot.error);
    return snapshot.hasData
      ? TransactionCardWidget(snapshot.data)
      : Center(child: CircularProgressIndicator());
  },
),

1 个答案:

答案 0 :(得分:3)

如果小部件是StatelessStateful,而您正在调用setState,则通过调用Future<List<TransactionsModel>>将创建fetchTransactions的新实例,从而使一个新的请求。您需要将函数返回的Future保存在State的{​​{1}}中,然后在StatefulWidget函数中调用fetchTransactions

initState