我想在我的 StreamBuilder 的 Stream 中使用 try{} catch(){},因為 ${globals.currentUid} 最初設定為 ''(empty string) 并在程式第一次運行時出現例外,但我找不到任何在流中嘗試捕獲的方法。
下面是我的streamBuilder
StreamBuilder(
stream: FirebaseFirestore.instance
.collection(
'user/${globals.currentUid}/friends')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasError) {
return Text(
'Error: ${snapshot.error}',
);
}
final docs = snapshot.data!.docs;
return Text(
docs.length.toString(),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
));
}),
此代碼產生此錯誤: _AssertionError ('package:cloud_firestore/src/firestore.dart': Failed assertion: line 63 pos 7: '!collectionPath.contains('//')': a collection path must not contain "// ")
我想做的是下面這個,
try{
StreamBuilder(
stream: FirebaseFirestore.instance
.collection(
'user/${globals.currentUid}/friends')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasError) {
return Text(
'Error: ${snapshot.error}',
);
}
final docs = snapshot.data!.docs;
return Text(docs.length.toString(),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
));
})
} on _AssertionError catch(e){
return Text('0',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
));
}
這在語法上是錯誤的。有什么解決辦法嗎?
uj5u.com熱心網友回復:
這種情況下的例外實際上不是由流產生的,而是由collection使用無效引數呼叫的方法產生的。您可能希望完全避免創建StreamBuilderuntilglobals.currentUid已使用有效值初始化。
您可以使用簡單的if陳述句或三元條件運算子來做到這一點。例如,假設您的 StreamBuilder 是容器的子項:
Container(
child: globals.currentUid != '' ?
StreamBuilder( // This will be built only if currentUid is not empty
stream: FirebaseFirestore.instance
.collection(
'user/${globals.currentUid}/friends')
.snapshots(),
builder: (
BuildContext context,
AsyncSnapshot snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
final docs = snapshot.data!.docs;
return Text(
docs.length.toString(),
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
);
},
)
: Container(), // An empty container will be shown if currentUid is empty
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476484.html
