2

I've been trying to create a list of Flutter Widgets to use them in a slider.
I'm fetching the data from JSON file, and passing it as Future<List> to FutureBuilder.
However, when trying to build my app, Error message pops up:

Error: Operator '[]' cannot be called on 'List<dynamic>?' because it is potentially null. 'List' is from 'dart:core'.

I've tried to validate it with 'initial data' or checking if it's not null, but they don't seem to work.
Is there some nice solution to get a list of Widgets just like ItemBuilder from ListView.builder does it?
NOTE: when I build app with static data, and then perform hot reload it fetches data just fine, and shows no exceptions or warnings.

List<Widget> elements = [];
if (snapshot.hasData) {
  for(int j = 0; j < snapshot?.data?.length; ++j) {
    elements.add(
      Container(child: Text(snapshot.data[j]["my_text"])
    )
  );
}
Heinzest
  • 21
  • 4

1 Answers1

1

You need an object in your list like this:

Future<List<Album>> fetchAlbum() async { //Album is an object
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class Album {
  final int userId;
  final int id;
  final String title;

  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

if (snapshot.hasData) {
  return Text(snapshot.data!.title); //title is String in Album
} else if (snapshot.hasError) {
  return Text("${snapshot.error}");
}
kietle
  • 153
  • 6