我试图弄清楚我的 StreamBuilder/Stream 的问题是什么:
Stream<Page> pageStream;
@override
void initState() {
super.initState();
final firestoreService = Provider.of<FirestoreService>(context, listen: false);
final book = Provider.of<Book>(context, listen: false);
final pageNumber = Provider.of<int>(context, listen: false);
pageStream = firestoreService.getStreamOfPage(bookId: book.bookId, pageNumber: pageNumber);
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: pageStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting ||
snapshot.connectionState == ConnectionState.none) {
return CupertinoActivityIndicator();
}
if (snapshot.hasError) {
return Text('the error is = ${snapshot.error.toString()}');
}
Page page = snapshot.data;
return Container(
color: Colors.purple,
height: 30,
width: 30,
);
}
);
}
因此,在 initstate 方法中,我得到了存储在状态中然后分配给 StreamBuilder 的流。
获取 Stream 的方法是:
Stream<Page> getStreamOfPage(
{@required String bookId, @required int pageNumber}) {
try {
Stream<Page> pageStream = _fireStore
.document('books/$bookId/$pageNumber')
.snapshots()
.map((docSnapshot) => Page.fromMap(map: docSnapshot.data));
return pageStream;
} catch (e) {
print(
'Could not get stream of page with bookId = $bookId and pageNumber = $pageNumber');
print(e);
return null;
}
}
我在构造函数 Page.fromMap() 中编写的打印语句(包括构造函数末尾的一个)已执行,因此我假设错误不存在。我在 map 方法中添加的打印语句(来自 .snapshots().map(...))没有执行,这对我来说没有意义,因为 Page 构造函数中的语句被执行(使用来自 firebase 文档的正确值)。
调用栈如下:
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23c7127e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff513fbb20 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23c70ff8 +[NSException raise:format:arguments:] + 88
3 Foundation 0x00007fff256e9c1a -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 166
4 Runner 0x00000001018ca524 _ZN8firebase9firestore4util16ObjcThrowHandlerENS1_13ExceptionTypeEPKcS4_iRKNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEE + 356
5 Runner 0x00000001018c9d63 _ZN8firebase9firestore4util5ThrowENS1_13Except<…>