Home > Software design >  How do I Display Nested json array in flutter?
How do I Display Nested json array in flutter?

Time:11-02

Whenever I try accessing a field from the nested array I get the following Range error. Not sure what's gone wrong, any help would be appreciated.

RangeError (index): Invalid value: Only valid value is 0: 1

This is my User Model :

import 'dart:convert';

List<User> userFromJson(String str) =>
    List<User>.from(json.decode(str).map((x) => User.fromJson(x)));

class User {
  User({
    required this.userName,
    required this.facilities,
  });

  final String userName;

  final List<Facility>? facilities;

  factory User.fromJson(Map<String, dynamic> json) => User(
        userName: json["userName"],
        facilities: json["facilities"] == null
            ? null
            : List<Facility>.from(
                json["facilities"].map((x) => Facility.fromJson(x))),
      );
}

class Facility {
  Facility({
    required this.id,
    required this.employeeGlobalId,
    required this.facilityId,
  });

  final int id;
  final int employeeGlobalId;
  final int facilityId;

  factory Facility.fromJson(Map<String, dynamic> json) => Facility(
        id: json["id"],
        employeeGlobalId: json["employeeGlobalId"],
        facilityId: json["facilityId"],
      );
}

This is how I connect with the API and convert the response to a list.

class ApiService {
  final url = Uri.parse("http://47.254.237.237:81/api/Users/GetAllUser");
  Map<String, String> headers = {
    "Accept": 'application/json',
    'content-type': 'application/json',
    'Authorization':
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyIiwibmJmIjoxNjY2OTU0NTEzLCJleHAiOjE2NjcwNDA5MTMsImlhdCI6MTY2Njk1NDUxM30.EXEzTX8-MHQqZuuILwHGoQ0Vpw2fAgsi2QypGNFgMAE',
    'userId': '62'
  };

  Future<List<User>> fetchUsers(http.Client client) async {
    final response = await client.get(url, headers: headers);
    return compute(parseUsers, response.body);
  }

  List<User> parseUsers(String response) {
    final parsed = jsonDecode(response).cast<Map<String, dynamic>>();
    return parsed.map<User>((json) => User.fromJson(json)).toList();
  }
}

Lastly, This is how I am trying to display the facility ID.

ListView.builder(
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(users[index].userName),
          subtitle: Text(users[index].facilities![index].facilityId.toString()),
        );
      },
    );

CodePudding user response:

Probably facilities![index] is causing the issue. You're trying to access facilities values at index range, builder's current position, while only one value might be available.

Change to facilities![0]. Or use loop/map fn to print each facilities if there are more than 1 facilities values.

Updated code:

ListView.builder(
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(users[index].userName),
          subtitle: Text(users[index].facilities![0].facilityId.toString()),
        );
      },
    );
  • Related