0

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()),
        );
      },
    );
1
  • That was just for testing, Please take a look where I'm using the index below in subtitle. Commented Nov 2, 2022 at 10:19

1 Answer 1

1

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()),
        );
      },
    );
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thank you buddy, I couldn't think of a logic that simple ! stupid me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.