【问题标题】:Is there a way to to show snapshot data based on object value in Dart / Flutter (REST)?有没有办法根据 Dart / Flutter (REST) 中的对象值显示快照数据?
【发布时间】:2021-12-25 05:45:57
【问题描述】:

我只想显示包含数字 1 的帖子。

JSON:

posts = '{"number":"1"}';

JSON 被提取到一个单独的文件中,例如:

    Posts(Map<String, dynamic> json) : super(json) {
        posts = json["number"];
    }

我有这个:

  Widget _buildGridView() => StreamBuilder<List<Posts>?>(
      builder: (context, snapshot) {
        if (snapshot.data != null) {
          return new GridView.count(
              children: List.generate(snapshot.data!.length, (index) {
                return _buildPlacesCell(snapshot.data![index]);
              }));
        }
      });

我想知道:我可以这样做吗?

if (snapshot.data.posts.number = 1)

代替

snapshot.data != null

还是不行?

我只想在帖子的 JSON 文件中包含数字 1 时才显示我的数据,但我无法让它工作。

我收到以下错误:

error: The getter 'posts' isn't defined for the type 'List<Post>'

编辑:在Jamiu的sn-p之后,得到以下错误:

错误:没有为类型“Post”定义运算符“[]”。

和:

错误:主体可能正常完成,导致 'null' 返回,但返回类型可能是不可为空的类型

【问题讨论】:

    标签: json wordpress flutter rest dart


    【解决方案1】:

    //试试这个

    Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
    if(data["number"]=="1"){
       //do
    }
    

    【讨论】:

    • 嗯,到底怎么样?你能看到我更新的代码吗?我没有地方可以添加它。
    【解决方案2】:

    您可以嵌套 if 语句。首先,检查snapshot.data != null,然后在 if 语句中,检查 snapshot.data.posts.number = 1 是否像这样:

    if(snapshot.data!=null){
        if(snapshot.data.posts.number=1){
            return new GridView.count(
            children: List.generate(snapshot.data!.length, (index) {
            return _buildCell(snapshot.data![index]);
            }));
        }
    }
    

    考虑这样做:

    StreamBuilder<List<Place>>(
        stream: listPosts,
        builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasData) {
                final data = snapshot.data!;
                if (data.isNotEmpty) {
                    return GridView.count(
                        children:[
                            for(var post in data)
                                if (post.number == '1')  _buildPlacesCell(post);
                        ],
                    );
                }else{
                    return const Center(
                        Text('No posts to display');
                    );
                }
            }
            if (snapshot.hasError) {
                print(snapshot.error);
                //! do any error handling here
            }
            return const Center(child: CircularProgressIndicator());
            },
        ),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2021-07-01
      • 1970-01-01
      • 2023-04-07
      • 2021-04-02
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多