Flutter-提供程序-如何基于提供程序的值更改UI?

问题描述 投票:0回答:1

我想根据从流提供者处获得的对象值来使用两种形式的UI。

在小部件中,我得到这样的对象:

final recentPostData = Provider.of<List<RecentPostData>>(context) ?? [];

然后,我想根据最近的PostData属性更改UI:

return SingleChildScrollView(
      child: Column(children: [
        (recentPostData[0].attribute != '123') ?
          RaisedButton( ... )
        : SizedBox( ... ),

问题:流值进入延迟,因此出现初始错误:“ RangeError(索引):无效值:有效值范围为空: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
1个回答
0
投票

[我认为在构建窗口小部件之前,检查lastPostData的大小可以解决您的问题。以下代码可能会对您有所帮助。

recentPostData.length > 0 ? (recentPostData[0].attribute != '123') ?
          RaisedButton( ... )
        : SizedBox( ... ) : Text(" show Loading indicator")
© www.soinside.com 2019 - 2024. All rights reserved.