Home > Software design >  How to convert Map<String, dynamic> to Map<int, String> in flutter
How to convert Map<String, dynamic> to Map<int, String> in flutter

Time:09-27

Here is the expected map

{
    1: '1000',
    2: '400',
    3: '800',
    4: '7000',
    5: '5000',
    6: '300',
    7: '2000',
    8: '100',
  };

I tried to create it in firestore as seen below enter image description here

This is my model range carries this particularly map

class PackageModel {
  String? id;
  final String? name;
  String? description;
  int? price;
  String? pcolor;
  String? img;
  Map? range;

  PackageModel({
    this.id,
    this.name,
    this.description,
    this.price,
    this.img,
    this.pcolor,
    this.range,
  });

  static PackageModel fromJson(Map<String, dynamic> json) => PackageModel(
        id: json['id'],
        name: json['name'],
        description: json['description'],
        price: json['price'],
        img: json['img'],
        pcolor: json['pcolor'],
        range: json['range'],
      );
}

Now I want to consume the range here:

updatePackageRange(pack.range as Map<int, String>);

But I ran into this issue

Exception has occurred.
_CastError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<int, String>' in type cast)

How to I make this <String, dynamic> to be <int, String>

CodePudding user response:

You'll need to be more specific with the conversion of the range field, and range should also have the type Map<int, String>.

An updated version of your class might look something like this:

class PackageModel {
  String? id;
  final String? name;
  String? description;
  int? price;
  String? pcolor;
  String? img;
  Map<int, String>? range;

  PackageModel({
    this.id,
    this.name,
    this.description,
    this.price,
    this.img,
    this.pcolor,
    this.range,
  });

  static PackageModel fromJson(Map<String, dynamic> json) => PackageModel(
        id: json['id'],
        name: json['name'],
        description: json['description'],
        price: json['price'],
        img: json['img'],
        pcolor: json['pcolor'],
        range: json['range'].map<int, String>(
          (key, value) =>
              MapEntry<int, String>(int.parse(key), value.toString()),
        ),
      );
}
  • Related