Flutter StreamBuilder从Firestore返回null

时间:2019-05-14 13:11:56

标签: firebase dart flutter google-cloud-firestore

这个想法是在Firebase的集合中显示随机文档中的字符串。一个简单的函数getRandom()检索文档总数并生成一个随机整数r,该整数将被馈送到Firebase实例中。

应用中的输出始终为null

StreamBuilder(
        initialData: Words(),
          stream: getWords(),
          builder: (context, snapshot){

            if(!snapshot.hasData){
              return Center(child: Text("NO DATA"));
            }else {
              var r = snapshot.data;
              return Center(child: Text("${r.english}"));
            }
      })
Stream<Words> getWords() async* {
  int r = await getRandom();

  print("RANDOM NO: " + "$r");

  Firestore.instance.document("vocabs/foods/words/$r")
      .get()
      .then((snapshot){
    try {
      return Words().english;

    } catch(e){
      print("ERROR");
      return null;
    }
  });
}

class Words{

  Words(): super();

  String english;

  Words.fromSnapshot(DocumentSnapshot snapshot)
  : english = snapshot.data["english"];
}

Firestore DB part 1

Firestore DB part 2

1 个答案:

答案 0 :(得分:1)

我为您构建了这段示例代码,为您提供一些选择来实现您想做的事情:

import 'dart:async';

class Word {    
  final String english;
  const Word(this.english);
}

Future<Iterable<Word>> get firebaseSnapshot async => [ Word('aWord'), Word('bWord'), Word('cWord') ];

Stream<String> getEnglishWords() async* {
  yield* await firebaseSnapshot.then((words) => Stream.fromIterable(words.map((w) => w.english)));
}

Stream<String> getEnglishWords2() async* {    
  final words = await firebaseSnapshot.then((words) => words.map((w) => w.english));
  yield* Stream.fromIterable(words);
}

Stream<String> getEnglishWords3() async* {    
  final snapshot = await firebaseSnapshot;
  for(final word in snapshot) {
    yield word.english;
  }  
}

main() async {
  await for(final englishWord in getEnglishWords()) {
    print(englishWord);
  }

  await for(final englishWord in getEnglishWords2()) {
    print(englishWord);
  }

  await for(final englishWord in getEnglishWords3()) {
    print(englishWord);
  }
}

选项2是我要使用的选项。围绕它有一些重要的性能考虑。我正在为后面的演讲而烦恼……不,不记得了……如果找到它,我会更新的。