【发布时间】:2020-07-19 22:09:42
【问题描述】:
我想要基于从 Stream Provider 获得的对象值的两种形式的 UI。
在小部件中,我得到这样的对象:
final recentPostData = Provider.of<List<RecentPostData>>(context) ?? [];
然后,我想根据RecentPostData的一个属性来改变UI:
return SingleChildScrollView(
child: Column(children: [
(recentPostData[0].attribute != '123') ?
RaisedButton( ... )
: SizedBox( ... ),
问题:传入的流值有延迟,因此我得到了初始错误: "RangeError(index):无效值:有效值范围为空:0"
因此,我尝试使用多个条件 - 因此首先检查 (recentPostData != []),然后检查第二个条件,但这不起作用(出现相同的错误)。
你知道如何解决这个问题吗?
非常感谢!
class _PostFeedState extends State<PostFeed> {
bool isLoading = false; // track if products fetching
@override
Widget build(BuildContext context) {
var recentPostData = Provider.of<List<RecentPostData>>(context) ?? [];
getProducts() async {
if (!hasMore) {
print('No More Products');
return;
}
if (isLoading) {
return;
}
setState(() {
isLoading = true;
});
QuerySnapshot querySnapshot;
if (lastDocument == null) {
querySnapshot = await firestore
.collection('posts')
.orderBy('timestamp', descending: true)
.limit(documentLimit)
.getDocuments();
print(0);
} else {
querySnapshot = await firestore
.collection('posts')
.orderBy('timestamp', descending: true)
.startAfterDocument(lastDocument)
.limit(documentLimit)
.getDocuments();
print(1);
}
if (querySnapshot.documents.length < documentLimit) {
hasMore = false;
}
if (querySnapshot.documents.length == 0) {
setState(() {
hasMore = false;
isLoading = false;
});
return;
}
lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];
products.addAll(querySnapshot.documents);
setState(() {
isLoading = false;
});
}
if (init) {
getProducts();
setState(() {
init = false;
});
}
void loadNewPosts() {
setState(() {
products = [];
lastDocument = null;
});
getProducts();
}
return SingleChildScrollView(
child: Column(children: [
(recentPostData != []) ? (recentPostData[0].pid != DatabaseServicePosts().postDataFromSnapshot(products[0]).pid) ?
RaisedButton(
onPressed: () {
loadNewPosts();
setState(() {
hasNew = false;
});
},
child: Text('New Posts Available'),
color: Colors.green[300],
)
: SizedBox(height: 0) : SizedBox(height: 0),
products.length == 0
? Center(
child: Text('No Data...'),
) :
Column(children: <Widget>[
...products.map((el) => PostTile (postData: DatabaseServicePosts().postDataFromSnapshot(el))),
],),
(hasMore && !init) ?
RaisedButton(
onPressed: () {
getProducts();
},
child: Text(
'More Posts',
style: TextStyle(color: Colors.white),
),
color: Colors.lightBlue[200],
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(102.0),
side: BorderSide(color: Colors.blueGrey[400])
),
)
: Padding(
padding: const EdgeInsets.all(10.0),
child: Container(child: Text('No more Posts')),
),
isLoading
? Container(
child: Text('Loading'),
)
: Container(),
SizedBox(height: 10),
]
),
);
}
}
【问题讨论】:
标签: firebase flutter conditional-statements provider