我正在尝试找出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方法内添加的Print语句(来自.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<…>
答案 0 :(得分:0)
我找到了使之工作的方法。将获取流的函数更改为:
Stream<Page> getStreamOfPage(
{@required String bookId, @required int pageNumber}) {
try {
Stream<Page> pageStream = _fireStore
.document('books/$bookId')
.collection('pages')
.where('pageNumber', isEqualTo: pageNumber)
.snapshots()
.map((snap) => Page.fromMap(map: snap.documents[0]?.data));
return pageStream;
} catch (e) {
print(
'Could not get stream of page with bookId = $bookId and pageNumber = $pageNumber');
print(e);
return null;
}
}
我不确定为什么旧版本不起作用。