从Firestore获取数据并渲染到另一个功能DART

时间:2019-10-17 11:17:51

标签: firebase flutter dart google-cloud-firestore

我想从Firebase获取数据并将数据放入API,我有两个功能

这是从Firestore获取数据

_getLang() async{
  final FirebaseUser user = await FirebaseAuth.instance.currentUser();
  final String uid = user.uid.toString();
  DocumentReference documentReference = Firestore.instance.collection("userDetails").document(uid);
  documentReference.get().then((datasnapshot) {
    if (datasnapshot.exists) {
      return datasnapshot.data['lang'].toString();
    }
    else{
      return " ";
    }
  });
}

和这个从API提取数据的

Future<List<Book>> getBooks(title) async {
  var random = Random.secure();
  var value = random.nextInt(300);
  http.Response response = await http.get(
      'https://www.googleapis.com/books/v1/volumes?q=subject:flutter&orderBy=newest&maxResults=7&printType=books&langRestrict='+_getLang()', headers:{"Accept":"aplication/json"});
  List<Book> books = new List<Book>();
  var responseJson = json.decode(response.body);
  if (responseJson["items"] != null)
    responseJson["items"].forEach((v) => books.add(Book.fromJson(v)));
  return books;
}

1 个答案:

答案 0 :(得分:1)

您不能通过_getLang()的异步方式来做到这一点。

将getBooks()重写为此:

Future<List<Book>> getBooks(title) async {
  var myLang = await _getLang();
  var random = Random.secure();
  var value = random.nextInt(300);
  http.Response response = await http.get(
      'https://www.googleapis.com/books/v1/volumes?q=subject:flutter&orderBy=newest&maxResults=7&printType=books&langRestrict='+myLang, headers:{"Accept":"aplication/json"});
  List<Book> books = new List<Book>();
  var responseJson = json.decode(response.body);
  if (responseJson["items"] != null)
    responseJson["items"].forEach((v) => books.add(Book.fromJson(v)));
  return books;
}