Map<String,dynamic> to Map<String, Map<String, String>> in Dart - dart

I am trying to convert Map<String,dynamic> to Map<String, Map<String, String>> in Dart
Map<String,dynamic> oldMap = querySnapshot.docs.first.data()["cach"];
Map<String, Map<String, String>> newMap = oldMap.map((a, b) => MapEntry(a, b as Map<String, String>));
But I got an error:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast

import 'dart:convert';
const rawData = '''
{"a": {"b": "c"}, "d":{"e": "f"}}
''';
Map<String, String> convert(Map<String, dynamic> data) {
return Map<String,String>.fromEntries(data.entries.map<MapEntry<String,String>>((me) => MapEntry(me.key, me.value)));
}
void main(List<String> args) {
var oldMap = jsonDecode(rawData) as Map<String, dynamic>;
var newMap = Map.fromEntries(oldMap.entries.map((me) => MapEntry(me.key, convert(me.value))));
print(newMap.runtimeType);
}
Result:
_InternalLinkedHashMap<String, Map<String, String>>

Related

type 'JSArray<dynamic>' is not a subtype of type 'List<Ad>'

I tried two method to parse the rawData into dart objects. One using a for loop ads and it works but why _ads is not working when I use map ?
void main() {
dynamic rawData = [
{"title": "a", "id": 1}
];
List<Ad> ads = [];
for (var raw in rawData) {
Ad ad = Ad.fromJson(raw);
ads.add(ad);
}
print(ads);
List<Ad> _ads = rawData.map((e) => Ad.fromJson(e)).toList();
print(_ads);
}
class Ad {
Ad({
this.id,
this.title,
});
int id;
String title;
factory Ad.fromJson(Map<String, dynamic> json) => _$AdFromJson(json);
Map<String, dynamic> toJson() => _$AdToJson(this);
}
Ad _$AdFromJson(Map json) {
return Ad(
id: json['id'] as int,
title: json['title'] as String,
);
}
Map<String, dynamic> _$AdToJson(Ad instance) {
final val = <String, dynamic>{};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('id', instance.id);
writeNotNull('title', instance.title);
return val;
}
The result of calling nearly any method on a dynamic defined variable are going to be dynamic since the Dart compiler are going through a difficult time guessing the type you want. So when you want the result to be saved into a variable with a specific type like List<Ad> _ads you really need to tell the compiler at each step what generic type you want and expect.
With that said, you can get you code to work by changing:
List<Ad> _ads = rawData.map((e) => Ad.fromJson(e)).toList();
Into:
List<Ad> _ads = rawData.map<Ad>((e) => Ad.fromJson(e)).toList();
And if you also want to make the analyzer happy:
List<Ad> _ads = rawData.map<Ad>((Map<String, dynamic> e) => Ad.fromJson(e)).toList() as List<Ad>;

How to create a Map in a loop?

i try to build a map to add it into firestore.
Produkt Class:
class Produkt{
String name;
int anzahl;
Produkt({
this.name,
this.anzahl,
});
factory Produkt.fromJson(Map<String, dynamic> parsedJson){
return Produkt(
name:parsedJson['Name'],
anzahl:parsedJson['Anzahl']
);
}
Map<String, dynamic> toProduktJson() =>
{
"Name" : name,
"Anzahl" : anzahl
};
}
ProduktList Class:
class ProduktList{
final List<Produkt> produkte;
ProduktList({
this.produkte,
});
factory ProduktList.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson["Produkte"] as List;
List<Produkt> produkte = list.map((i) => Produkt.fromJson(i.cast<String, dynamic>())).toList();
return ProduktList(
produkte: produkte,
);
}
Map<String, dynamic> toProdukteJson() =>
{
"Produkte" : [
produkte[0].toProduktJson(),
produkte[1].toProduktJson(),
produkte[2].toProduktJson(),
]
};
}
I wanted that the Map looks like:
{
"Produkte" : [
produkte[0].toProduktJson(),
produkte[1].toProduktJson(),
produkte[2].toProduktJson(),
]
};
But if the List produkte has a length of 2, the Map should have 2 and it the List have a length of 10, the Map should have 10 entries.
How can i do this?
Pls help me.
Thank you
An option would be the following:
Map<String, dynamic> toProdukteJson() {
Map map = new Map<String, dynamic>();
if (produkte != null) {
map["produkte"] = produkte.map((produkt) => produkt.toJson()).toList();
}
return map;
}
class Produkt {
final String id;
...
Produkt(this.id, ...);
Map toJson() => {'id' : id, ...};
}

How to fix type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

i created a method and when i built it, this error comes:
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
Then i deleted the method and the error is still there.
Here my Code:
class Produkt{
String name;
int anzahl;
Produkt({
this.name,
this.anzahl,
});
factory Produkt.fromJson(Map<String, dynamic> parsedJson){
return Produkt(
name:parsedJson['Name'],
anzahl:parsedJson['Anzahl']
);
}
Map<String, dynamic> toProduktJson() =>
{
"Name" : name,
"Anzahl" : anzahl
};
}
Class ProduktList
class ProduktList{
final List<Produkt> produkte;
ProduktList({
this.produkte,
});
factory ProduktList.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson["Produkte"] as List;
List<Produkt> produkte = list.map((i) => Produkt.fromJson(i.cast<String, dynamic>())).toList();
return ProduktList(
produkte: produkte,
);
}
Map<String, dynamic> toProdukteJson() =>
{
"Produkte" : [
produkte[0].toProduktJson(),
produkte[1].toProduktJson(),
]
};
}
I think the error comes from here, but i am not sure:
datenUebertragen(int index, AsyncSnapshot<QuerySnapshot> snapshot, ProduktList produkte){
Firestore.instance.runTransaction((transaction) async{
await transaction.update(
Firestore.instance.collection("Benutzer").document("Anton").collection("Einkaufsliste").document(
snapshot.data.documents[index].documentID),
produkte.toProdukteJson()
);
}
);
}
I call this method on an IconButton onPressed.
Can anyone help me?
Thank you
EDIT:
I call it like this:
ProduktList produkte = new ProduktList.fromJson(snapshot.data.documents[index].data);
the data look like:
{Produkte: [{Anzahl: 201, Name: Zucker}, {Anzahl: 10, Name: Backpulver}]}
EDIT:
It looks like this!
EDIT:
try changing this :
var list = parsedJson["Produkte"] as List;
to this :
final List list = parsedJson["Produkte"] as List;

Dart - How can I Map String & Int together?

static Future<String> compress({#required String imageSrc, #required int desiredQuality}) async {
final Map<String, dynamic> params = <String, dynamic> {
'filePath': imageSrc.toString()
};
I'm trying to add desiredQuality on the "params" map, but that's an int, how can I do it?
EDIT:
Turns out I didn't need to map int, all I had to do was this:
static Future<String> compress({#required String imageSrc, #required int desiredQuality}) async {
final Map<String, dynamic> params = <String, dynamic> {
'filePath': imageSrc,
'desiredQuality': desiredQuality
};
Thanks to #MarcG and #Gunter
A Map object could contain a collection of key/value pairs. Since you're trying to assign imageSrc (String) and desiredQuality (int) values on a Map<String, dynamic>, you can assign keys for each of these values in the Map.
Map<String, dynamic> params = {
'filePath': imageSrc,
'desiredQuality': desiredQuality
};
To access these key/values set in the Map, you can call them using:
var filePath = params['filePath'];
var desiredQuality = params['desiredQuality'];

FireStore and Flutter

I am writing an android app with flutter and Firestore at the backend database.
I can add single data to Firestore, but when I add an object with the nested object it fails. can't find any example or solution on google.
please help.
below is my code,
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';
part 'Inspection.g.dart';
//run code => flutter packages pub run build_runner build
#JsonSerializable()
class Inspection extends Object with _$InspectionSerializerMixin {
Inspection(
{this.inspectionDate,
this.staffName,
this.arrivedTime,
this.leaveTime,
this.foundLocation,
this.postName,
this.guestsProportion,
this.situationRemark,
this.userid,
this.id,
this.grooming});
String id;
#JsonSerializable(nullable: false)
DateTime inspectionDate;
#JsonSerializable(nullable: false)
String arrivedTime;
#JsonSerializable(nullable: false)
String leaveTime;
#JsonSerializable(nullable: false)
String staffName;
#JsonSerializable(nullable: false)
String postName;
#JsonSerializable(nullable: false)
String foundLocation;
#JsonSerializable(nullable: false)
String guestsProportion;
#JsonSerializable(nullable: false)
String situationRemark;
#JsonKey(nullable: false)
String userid;
#JsonKey(nullable: false)
Grooming grooming;
static Inspection fromDocument(DocumentSnapshot document) =>
new Inspection.fromJson(document.data);
factory Inspection.fromJson(Map<String, dynamic> json) =>
_$InspectionFromJson(json);
}
#JsonSerializable()
class Grooming extends Object {
int groomingScore;
int hairScore;
int uniformScore;
int decorationScore;
int maskWearScore;
int maskCleanScore;
Grooming();
factory Grooming.fromJson(Map<String, dynamic> json) =>
_$GroomingFromJson(json);
}
and this is generated by build_runner
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Inspection.dart';
// **************************************************************************
// Generator: JsonSerializableGenerator
// **************************************************************************
Inspection _$InspectionFromJson(Map<String, dynamic> json) => new Inspection(
inspectionDate: json['inspectionDate'] == null
? null
: DateTime.parse(json['inspectionDate'] as String),
staffName: json['staffName'] as String,
arrivedTime: json['arrivedTime'] as String,
leaveTime: json['leaveTime'] as String,
foundLocation: json['foundLocation'] as String,
postName: json['postName'] as String,
guestsProportion: json['guestsProportion'] as String,
situationRemark: json['situationRemark'] as String,
userid: json['userid'] as String,
id: json['id'] as String,
grooming: new Grooming.fromJson(json['grooming'] as Map<String, dynamic>));
abstract class _$InspectionSerializerMixin {
String get id;
DateTime get inspectionDate;
String get arrivedTime;
String get leaveTime;
String get staffName;
String get postName;
String get foundLocation;
String get guestsProportion;
String get situationRemark;
String get userid;
Grooming get grooming;
Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'inspectionDate': inspectionDate?.toIso8601String(),
'arrivedTime': arrivedTime,
'leaveTime': leaveTime,
'staffName': staffName,
'postName': postName,
'foundLocation': foundLocation,
'guestsProportion': guestsProportion,
'situationRemark': situationRemark,
'userid': userid,
'grooming': grooming
};
}
Grooming _$GroomingFromJson(Map<String, dynamic> json) => new Grooming()
..groomingScore = json['groomingScore'] as int
..hairScore = json['hairScore'] as int
..uniformScore = json['uniformScore'] as int
..decorationScore = json['decorationScore'] as int
..maskWearScore = json['maskWearScore'] as int
..maskCleanScore = json['maskCleanScore'] as int;
abstract class _$GroomingSerializerMixin {
int get groomingScore;
int get hairScore;
int get uniformScore;
int get decorationScore;
int get maskWearScore;
int get maskCleanScore;
Map<String, dynamic> toJson() => <String, dynamic>{
'groomingScore': groomingScore,
'hairScore': hairScore,
'uniformScore': uniformScore,
'decorationScore': decorationScore,
'maskWearScore': maskWearScore,
'maskCleanScore': maskCleanScore
};
}
code used to insert data
Future<bool> addInspection(Inspection item) async {
print('creating');
var newdoc = await inspectionCollection.document().get();
item.id = newdoc.documentID;
item.userid = user.uid;
inspectionCollection.add(item.toJson()).then((onValue) {
onValue.setData({'id': onValue.documentID});
}).catchError((error) {
print(error.toString());
});

Resources