0

Did this according to this manual https://www.bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/ Dart/Flutter parse array of JSON objects into List

JSON that comes from the server

{"myChannels":[{"id":"2","name":"channel2test","imageUrl":"image1.png"},{"id":"2","name":"channel2test","imageUrl":"image2.png"}]}

Model Class

class ChannelModel {
  String channelID;
  String channelName;
  String imageUrl;
  ChannelModel(this.channelID, this.channelName, this.imageUrl);

  factory ChannelModel.parsingChannels(dynamic json) {
    return ChannelModel(json['channelID'] as String,
        json['channelName'] as String, json['imageUrl'] as String);
  }
  @override
  String toString() {
    return '{ ${this.channelID}, ${this.channelName}, ${this.imageUrl} }';
  }
}

Main block

    try {
      final response = await http.post(
        url,
        body: json.encode({
          'action': 'getMyChannels',
          'userID': userID,
          'returnSecureToken': true,
        }),
      );
      //  print(jsonDecode(response.body));

      var extractedData =
          jsonDecode(response.body)['myChannels'] as List<dynamic>;
      List<ChannelModel> channelObjects = extractedData
          .map((cJson) => ChannelModel.parsingChannels(cJson))
          .toList();

      print(channelObjects);
   
      channelObjects.forEach((Data) {
        print('test');           
      });

the results is the following...

print(channelObjects) > outputs > []
print('test') > not working , channelObjects not looping 

2 Answers 2

2

I would suggest serializing your response to dart classes. It would be much easier to access the data you want.

class ApiResponse {
  ApiResponse({
    required this.myChannels,
  });

  List<MyChannel> myChannels;

  factory ApiResponse.fromJson(Map<String, dynamic> json) => ApiResponse(
        myChannels: List<MyChannel>.from(
          json["myChannels"].map((x) => MyChannel.fromJson(x)),
        ),
      );
}

class MyChannel {
  MyChannel({
    required this.id,
    required this.name,
    required this.imageUrl,
  });

  String id;
  String name;
  String imageUrl;

  factory MyChannel.fromJson(Map<String, dynamic> json) => MyChannel(
        id: json["id"],
        name: json["name"],
        imageUrl: json["imageUrl"],
      );
}

Then you can use it this way :

final extractedData = ApiResponse.fromJson(json.decode(response.body) as Map<String, dynamic>);

And access the data you want

extractedData.myChannels[0].id
extractedData.myChannels[0].name
extractedData.myChannels[0].imageUrl

for (var ch in extractedData.myChannels){
 print(ch.id);
 print(ch.name);
 print(ch.imageUrl);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like your approach, but I could not fix my problem with it, don't know why, then I spent a bit more time , found an article with example and updated my code according to that article. But again it does not work, can you check my code please and say what you think ?
0
part 'example.g.dart';

@JsonSerializable()
class Channel{
  final String id;
  final String name;
  final String? imageUrl;
  Channel({required this.id, required this.name, this.imageUrl});
  factory Channel.fromJson(Map<String, dynamic> json) => _$ChannelFromJson(json);
  Map<String, dynamic> toJson() => _$ChannelToJson(this);
}



@JsonSerializable()
class ChannelList{
  final List<Channel> myChannels;
  ChannelList({required this.myChannels});
  factory ChannelList.fromJson(Map<String, dynamic> json) => _$ChannelListFromJson(json);
  Map<String, dynamic> toJson() => _$ChannelListToJson(this);
}

final extractedData = ChannelList.fromJson(json.decode(response.body));

https://pub.dev/packages/json_serializable

Using JsonSerializable more useful and understandable. You can read documentation of that package

Comments

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.