Converting Set of a Map to a Map - flutter

I need help in converting an argument type from Set to a Map. I using batch update in my flutter code and '.toJson()' method to get the 'data'.
The warning I get is :
The argument type 'Set<Map<String,dynamic>>' can't be assigned to the parameter type 'Map<String,dynamic>'.
..for the 'data' part in batchUpdate command.
Is there any way to convert the set to a Map so batch.Update can accept it?

We may first convert your data from .toJson() method like this code below :
// 1. As explained, toJson() results `data` typed as Set<Map<String, dynamic>>
Set<Map<String, dynamic> data = payload.toJson()
// 2. Convert `data` type to Map<String, dynamic>
Map<String, dynamic> newData = data.single
// 3. then proceed `data` to next method
batchUpdate(data);

Related

How do I extract values from a DataSnapshot returned by 'getting' a Firebase database reference in Flutter?

I'm building an app using Flutter and I'm trying to read data from my Firebase Realtime Database. I'm aware of the ability to listen to events on the database, but in this case I need to manually grab data. I'd like to be able to get a snapshot from a database reference as a Map<String, dynamic>, so that I can access my data via keys.
Here's the relevant code I'm using (within a stateful widget):
late Map<String, dynamic> codes;
void getData() async {
var snapshot = await database.ref('codes').get();
codes = snapshot.value;
}
#override
void initState() {
super.initState();
getData();
}
Printing snapshot.value displays a map as expected. Printing snapshot.value.runtimeType displays _InternalLinkedHashMap. But when I attempt to convert that to a Map<String, dynamic> it throws an error because snapshot.value has the type Object? (stated here). I'm also unable to just access data using a key for the same reason.
I tried all of the following with no success. All attempts returned errors relating to the difference in the object types.
// tried converting snapshot value to a Map
var data = snapshot.value as Map<String, dynamic>;
// also tried generating a Map using the 'from' constructor
var data = Map<String, dynamic>.from(snapshot.value);
// tried referencing a value straight from the snapshot value Object
var helpMe = snapshot.value['ABC123'];
What I was expecting was to be able to grab a snapshot and use it as a Map (because that's how the Realtime Database stores information) to access any data within the referenced node. I don't really understand why that wouldn't be exactly how it works, and if not, send me a JSON String I can decode myself.
It's been a long day, and I'm very tired, so I suspect I'm missing something very obvious. How can I convert this to a Map so I can easily access my data? And please don't tell me I'll need to iterate through the children property of the DataSnapshot to get my data, because that sounds unnecessarily painful.
Cheers!

In Flutter, an object's fromJson method generated by freezed occured type cast error, DateTime -> String

I have used freezed library to manage my Remote DTO classes and Ui Models.
In this question case, my Object LifeDiagnosisResult DTO and Ui Model only have one difference - createdAt field.
When I put data, I used SharedPreference (because backend is not yet built) and put my List value by jsonEncode function.
When I get a response from SharedPreference (because backend is not yet built) , I used jsonDecode to get Map Object.
To achieve my final wish, List Object, I added createdAt field like this.
void _handleListResponseSuccess(List<String> response) {
List<LifeDiagnosisResultUiModel>? uiModelList = response.map((e) {
Map<String, dynamic> map = jsonDecode(e) as Map<String, dynamic>;
map['createdAt'] = DateTime.now();
return LifeDiagnosisResultUiModel.fromJson(map);
}).toList();
if (uiModelList.isNotEmpty) {
setLifeDiagnosisResultUiModel(uiModelList[uiModelList.length - 1]);
}
_rxList(uiModelList);
}
But, when I ran this code, type casting error was caused.
The error message is this.
error type 'DateTime' is not a subtype of type 'String' in type cast
And this is my Ui Model's createdAt field.
I think Map's createdAt could not find correct field in Ui Model.
But I have no idea why...
Could you tell me what is wrong?
I found the answer...
it is not a real answer of my question, but it can explain why this issue happen.
In dart, Map's DateTime cannot be converted to Object's DateTime.
I dont know a detail process, but in type casting, Map's DateTime is converted to String type.
I don't know if I get it right, but if you want to test your fromJson method you could do it like this:
Map<String,dynamic> response={'att1':1234,'att2':'oneTwoThree','createdAt':DateTime(2022,08,22)};
return LifeDiagnosisResultUiModel.fromJson(response);

Migrating from Provider to Riverpod

I am stuck using Provider and came across Riverpod which is just the next gen of Provider. I am trying to create a StreamProvider using Riverpod but I am getting an error.
Here is the code for creating the StreamProvider:
final trxnStreamProvider = StreamProvider.autoDispose<List<Trxns>>((ref) {
final stream = firestoreService.getAgencyTrxns();
return stream.map((snapshot) => snapshot.docs.map((doc) => Trxns.fromFirestore(doc.data)).toList());
});
The error I get marks the code "doc.data". Here is the error text:
The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.
Here is the code for "Trxns.fromFirestore(doc.data)":
Trxns.fromFirestore(Map<String, dynamic> firestore)
: clientFName = firestore['clientFName'],
clientLName = firestore['clientLName'];
I'm still new to this and am having a hard time understanding the error message. Is it saying that "doc.data" is not the right type? If so, how do I fix this? If not, what is wrong and how do I fix it?
Map<String, dynamic> data() => dartify(jsObject.data());
data is a method so you need to call it:
doc.data()
doc.data mean you want to pass a function

The argument type 'List<String>' can't be assigned to the parameter type 'List<String>Function()'

I have a Map that consists of a String key and a List value. However when I try to add a new value to the Map, I get the error "The argument type 'List' can't be assigned to the parameter type 'ListFunction()'".
The sample code is as follows:
Map<String, List<String>> map = new Map<String, List<String>>();
String key = "Key1";
List<String> currentValues = [];
map.putIfAbsent(key,currentValues);
The last line throws the error above. Does anyone have a fix for this?
From the docs, putIfAbsent takes a function as a second argument. So you should write something like this :
map.putIfAbsent(key, () => currentValues);

How to correctly do type conversions in dart

I'm building a flutter app that uses Dog API but I am failing to convert the type of a Map to Map<String, List<String>>
I have tried to use map.cast<String,List<String>>() but while not producing an error when I try to return the result (after specifing that the function returns a Map<<String,List<String>>>), when I run print(map.runtimeType); the output is CastMap<String, dynamic, String, List<String>> and not Map<<String,List<String>>>
Future<Map<String,List<String>>> getbreeds() async{
var json=await http.get('https://dog.ceo/api/breeds/list/all');
var linkedHashMap =Map.from(jsonDecode(json.body)) ;
var map=linkedHashMap['message'].cast<String,List<String>>();
print(map.runtimeType);
return map;
}
I expect the output of print(map.runtimeType); to be Map<<String,List<String>>> but instead, I get CastMap<String, dynamic, String, List<String>>
A CastMap<String, dynamic, String, List<String>> is a subtype of Map<String, List<String>> so that isn't a problem here. It's comparable to a situation where you specify a return type of num and the concrete value you return is an int.
The issue you're going to hit is that when you read a value from the map you'll have a List<dynamic> instead of a List<String>. You need to change the runtime types on the inner values as well.
var map = (linkedHashMap['message'] as Map).map((key, value) => MapEntry<String, List<String>>(key, List.from(value));