Search code examples
jsonflutterflutter-futurebuilder

Flutter : show specified row from nested JSON data


I have future builder with future list like this ,I want to view data with empty predect object:

[
  {
    "id": 1,
    "home": "Turkey",
    "away": "Italy",
    "h_goals": 0,
    "a_goals": 0,
    "date": "2021-02-06",
    "time": "22:00",
    "predect": [
      {
        "id": 3,
        "user_id": 10,
        "match_id": 1,
        "h_predect": 1,
        "a_predect": 1,
        "player_id": 1,
        "point": 0,
        "username": "sar"
      }
    ]
  },
  {
    "id": 2,
    "home": "Denmark",
    "away": "Finland",
    "h_goals": 0,
    "a_goals": 0,
    "date": "2021-06-12",
    "time": "19:00",
    "predect": []
  },
]

I want to show the matches details that have empty predect ,I have this widget but not work:

return FutureBuilder(
            future: mathesProv.matchsWithUserPredects(username, token),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      var item = snapshot.data[index];
                      if (item.predect == null) {
                        return Text('${item.home}');
                      } else {
                        return Container(
                          child: Text('$index'),
                        );
                      }
                    });
              } else {
                return Text('loading');
              }
            });

How can I view rows that have empty predect list?


Solution

  • You forgot to add a check for length = 0

        return FutureBuilder(
            future: mathesProv.matchsWithUserPredects(username, token),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      var item = snapshot.data[index];
                      if ((item.predect == null)||(item.predect.length==0)) {
                        return Text('${item.home}');
                      } else {
                        return Container(
                          child: Text('$index'),
                        );
                      }
                    });
              } else {
                return Text('loading');
              }
            });