Home > front end >  Casting an Object/Objects to a List
Casting an Object/Objects to a List

Time:01-08

I have a JSON response fetched from MongoDB using Node.JS which I would like to parse. Right now, I'm trying to insert the objects to a List variable _data that I intend to use in my app. However, I'm getting an error for obvious reasons and the solution for which I don't know. The code and the error will follow after the response:

The response(I'm working with the district property at the moment):

[{_id: 619d1a4cba28db7dc392224f, district: Kolkata, types: [{category: Grievances}, {category: General}, {category: Urgent}, {category: Service}], ward_no: [{ward: 6, grievance: [{serial_number: 0001, name: Siddhartha Chatterjee, date: 2020-05-17 07:41:03, issue: Refund not paid, description: [Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua., Amet massa vitae tortor condimentum lacinia., Quis ipsum suspendisse ultrices gravida dictum fusce ut placerat orci., Ut aliquam purus sit amet luctus venenatis lectus magna., Tortor at auctor urna nunc id cursus metus aliquam eleifend., Dictum fusce ut placerat orci nulla pellentesque., Pharetra magna ac placerat vestibulum lectus mauris ultrices eros in., Eu facilisis sed odio morbi quis commodo odio aenean sed., Ut placerat orci nulla pellentesque dignissim enim sit amet venenatis., Morbi tincidunt augue interdum velit euismod in pellentesque massa placerat., Arcu vitae elementum curabitur vit

The code(Please note that my idea was to parse the data in the exact same way as the response above i.e List Of Objects):

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Model {
  final String district;

  Model({required this.district});
}

class ModelClass with ChangeNotifier {
  List<dynamic> _data = [];            //This is the list variable

  List<dynamic> get data {
    return[..._data];
  }

  Future<void> getData() async {
    final url = Uri.http('192.168.0.6:3007', '/fetchData');
    final response = await http.get(url);
    print(response);
    final extractedData = json.decode(response.body);
    print(extractedData);
    Map<String, Model> temp = {};
    extractedData.forEach((value) {
      temp.putIfAbsent(value['_id'], () => Model(
        district: value['district']
      ));
    });
    print(temp);              //Output given below
    _data = temp as List;     //This line throws the error
  }
}

The temp response:

{619d1a4cba28db7dc392224f: Instance of 'Model', 619d1a4cba28db7dc3922250: Instance of 'Model', 619d1a4cba28db7dc3922251: Instance of 'Model'}

The error:

Unhandled Exception: type '_InternalLinkedHashMap<String, Model>' is not a subtype of type 'List<dynamic>' in type cast

CodePudding user response:

Your temp variable is a map with _id as key and an instance of Model class as value. If you want to extract the Model instances into a list, you can do something like:

final List<Model> list = temp.values.toList();
  •  Tags:  
  • Related