1

My problem is, that when I try to map the brands I need to declare brandsData as a Map<String, dynamic> but in that case jsonDecode(s) is red because it could be null

1 Answers1

0

You can change your Model to this .

// To parse this JSON data, do
//
//     final album = albumFromJson(jsonString);
import 'dart:convert';

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

String albumToJson(List<Album> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

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

    int userId;
    int id;
    String title;

    factory Album.fromJson(Map<String, dynamic> json) => Album(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
    };
}

and use the function that @Ravindra via link like this

 Future<List<Album>> fetchPost() async {
      String url =
          'https://jsonplaceholder.typicode.com/albums/1';
      var response = await http.get(Uri.parse(url), headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      });
      if (response.statusCode == 200) {
        // If the call to the server was successful, parse the JSON
        return Album.fromJson(json
            .decode(response.body));
      } else {
        // If that call was not successful, throw an error.
        throw Exception('Failed to load post');
      }
    }

Hope it helps you. Lastly you can use this link https://app.quicktype.io/ to create your model class.

Faizan Darwesh
  • 301
  • 1
  • 5