Can someone help me to figure out, how to get the uid from my table?
When the user selects a row, then onSelect: onSelected is getting used.
This returns the selected row and the values (as example: true {uid: 1xorAjA7hRZfOdN3zpkAWI7spgp1, username: awdwa,...} - true means the row is selected, false the row is not selected)
Now I want to get the uid, so the first value of the Map<String, dynamic>.
My first step is to store all data in a variable: var selectedUid = userTable.onSelected, and then I need to get access to the Map<String, dynamic> to get the uid right?
But how can I get acess to the first value of Map<String, dynamic> when I have a (bool, Map <String, dynamic>)? Someone have an advice how I can do this?
Sorry, when this is a dumb question, but the (bool, Map <String, dynamic>) confuses me completly. Thank you a lot for your help.
code onSelected from table:
List<Map<String, dynamic>> selecteds = [];
onSelected(bool value, Map <String, dynamic> item){
print("$value $item ");
if (value) {
selecteds.add(item);
} else {
selecteds.removeAt(selecteds.indexOf(item));
}
notifyListeners();
}
Edit:
When I try to get the uid from the bool, Map<String, Dynamic> like this:
selectedId = userTable.getSelected,
print('Uid: '+selectedId[uid])
I get this error:
The following NoSuchMethodError was thrown while handling a gesture:
'[]'
Dynamic call of null.
Receiver: Instance of '(bool, Map<String, String>) => dynamic'
Arguments: ["M0glOQKUwagZJGOyzVEU1JJgQo23"]
When I try to safe the data in List<Map<String, dynamic>> and just try to get the first value, then I get the error:
Expected a value of type 'List<Map<String, dynamic>>', but got one of type '(bool, Map<String, dynamic>) => List<Map<String, dynamic>>'
code:
getSelected(bool value, Map <String, dynamic> item){
print("$value $item ");
if (value) {
selecteds.add(item);
return selecteds as List<Map<String, dynamic>>;
} else {
selecteds.removeAt(selecteds.indexOf(item));
}
notifyListeners();
}
Maps are not ordered. There is no "first" item. You probably meant to ask how to get the "uid" from the map?
You can use item["uid"].
Related
I am trying to get the JSON response from the server and output it to the console.
Future<String> login() async {
var response = await http.get(
Uri.encodeFull("https://etrans.herokuapp.com/test/2"),
headers: {"Accept": "application/json"});
this.setState(() {
data = json.decode(response.body);
});
print(data[0].name);
return "Success!";
}
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is
not a subtype of type 'List
What could be the reason?
Here are 2 common ways this could go wrong:
If your response is a json array like
[
{
key1: value1,
key2: value2,
key3: value3,
},
{
key1: value1,
key2: value2,
key3: value3,
},
.....
]
Then, we use data[0]["name"], not data[0].name
Unless we cast to an object that has the name property, we cannot use data[0].name
We cast like this data = json.decode(response.body).cast<ObjectName>();
ObjectName can be whatever object you want (Inbuilt or Custom). But make sure it has the name property
If your response is a JSON object like
{
dataKey: [
{
key1: value1,
key2: value2,
key3: value3,
}
]
}
Then json.decode will return a Map, not a List
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> data = map["dataKey"];
print(data[0]["name"]);
You can use
new Map<String, dynamic>.from(snapshot.value);
Easiest way (one dimensional):
Map<String, dynamic> data = new Map<String, dynamic>.from(json.decode(response.body));
print(data['name']);
You are trying to case an Instance of InternalLinkedHashMap which is not possible.
You should Serialize and deserialize it back to Map<String, dynamic>.
InternalLinkedHashMap<String, dynamic> invalidMap;
final validMap =
json.decode(json.encode(invalidMap)) as Map<String, dynamic>;
You have to convert the runtimeType of data from _InternalLinkedHashMap to an actual List.
One way is to use the List.from.
final _data = List<dynamic>.from(
data.map<dynamic>(
(dynamic item) => item,
),
);
If you need work with generic fields has a workaround:
class DicData
{
int tot;
List<Map<String, dynamic>> fields;
DicData({
this.tot,
this.fields
});
factory DicData.fromJson(Map<String, dynamic> parsedJson) {
return DicData(
tot: parsedJson['tot'],
//The magic....
fields : parsedJson["fields"] = (parsedJson['fields'] as List)
?.map((e) => e == null ? null : Map<String, dynamic>.from(e))
?.toList()
);
}
}
You can get this error if you are using retrofit.dart and declare the wrong return type for your annotated methods:
#GET("/search")
Future<List<SearchResults>> getResults();
// wrong! search results contains a List but the actual type returned by that endpoint is SearchResults
vs
#GET("/search")
Future<SearchResults> getResults();
// correct for this endpoint - SearchResults is a composite with field for the list of the actual results
This worked for me:
Create a List Data
Use Map to decode the JSON file
Use the List object Data to fetch the name of the JSON files
With the help of index and the list object I have printed the items dynamically from the JSON file
setState(){
Map<String, dynamic> map = json.decode(response.body);
Data = map["name"];
}
// for printing
Data[index]['name1'].toString(),
Seems like this error could pop up depending on various developer faults.
In my case, I was using an EasyLocalization key but without defining it under asset/lang/en_US.json file.
If your working with Firebase Cloud,make sure that you're not trying to add multiple data with same DocumentID;
firestore.collection('user').document(UNIQUEID).setData(educandos[0].toJson()).
To convert from _InternalLinkedHashMap<String, dynamic> to Map<String, double> I used
Map<String,double>.from(json['rates'])
I had the same error using json_annotation, json_serializable, build_runner. It occurs when calling the ClassName.fromJson() method for a class that had a class property (example: class User has a property class Address).
As a solution, I modified the generated *.g.dart files of each class, by changing Map<String, dynamic>) to Map<dynamic, dynamic>) in everywhere there is a deep conversion inside the method _$*FromJson
The only problem is that you have to change it again every time you regenerate your files.
I have an error on the "snap.snapshot.value" parameter in the following line "var map = Map <String, dynamic> .from (snap.snapshot.value);". The error is "The argument type 'Object?' can't be assigned to the parameter type 'Map <dynamic, dynamic>'. "
class _HomePageState extends State<HomePage> {
List<Posts> postsList = [];
#override
void initState() {
super.initState();
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((snap) {
var map = Map<String, dynamic>.from(snap.snapshot.value); <--- the error is here
postsList.clear();
map.forEach((key, value) {
var values = Map<String,dynamic>.from(map);
Posts posts = Posts
(
values['url'],
values['descrizione'],
values['data'],
values['ora']
);
postsList.add(posts);
});
Would you change a code like below?
From
var map = Map<String, dynamic>.from(snap.snapshot.value);
To
Map<String, dynamic> map = snap.snapshot.value as Map<String, dynamic>
This is because Map.from function accepts a Map<dynamic, dynamic> but you are passing the object instead. So to pass as the same use casting like below :
var map = Map<String, dynamic>.from(snap.snapshot.value as Map<dynamic, dynamic>);
In your Posts model, you need to remove any explicit object casting.
e.g. change from
`Posts.fromMap(Map<String, dynamic> map) {
comments: List<String>.from((map['comments'] as List<String>))
}`
to
`Posts.fromMap(Map<String, dynamic> map) {
comments: List<String>.from((map['comments'] as List))
}`
so it's cast as a List and no farther
I am linking cloud function to my Flutter model. Result is coming from Cloud-Function
print(result.data);
print(result.data.runtimeType);
GameModel _incomingGame = GameModel.fromJson(result.data);
print(result.data);
{
game: 'GTA',
played: ['ISODATE', ...]
}
print(result.data.runtimeType);
flutter: _InternalLinkedHashMap<String, dynamic>
GameModel
#JsonSerializable()
class GameModel {
String? game;
List? played;
GameModel(
this.game,
this.played,);
factory GameModel.fromJson(Map<String, dynamic> json) =>
_$GameModelFromJson(json);
Map<String, dynamic> toJson() => _$GameModelToJson(this);
}
game_model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'game_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GameModel _$GameModelFromJson(Map<String, dynamic> json) => GameModel(
json['game'] as String?,
json['played'] as List?,
);
Map<String, dynamic> _$GameModelToJson(GameModel instance) => <String, dynamic>{
'game': instance.game,
'played': instance.played,
};
The incoming data result's runtimeType shows that it is Map<String, dynamic> in the console. However, when I execute GameModel.fromJson(), it causes type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' in type cast.
I really don't get that why this is happening somehow? Even if I do something like below also causes the same type cast error.
GameModel _gameData = result.data;
var game = GameModel.fromJson(_gameData);
Is there any way that I can fix this?
Try this solution:
GameModel.fromJson((result.data as Map<dynamic, dynamic>).cast<String, dynamic>())
Try these solutions
GameModel _incomingGame = GameModel.fromJson(result.data as Map<String, dynamic>);
Or
GameModel _incomingGame = GameModel.fromJson(Map<String, dynamic>.from(result.data));
It also would be better if you check the types before executing type casts
If above solutions doesn't work, add the type when calling cloud functions
final func = FirebaseFunctions.instance.httpsCallable('gameFunction');
final result = await func<Map<String, dynamic>?>();
I had troubles regarding my application to cast my variables into certain types.
For example:
Map<dynamic> into Map<String, List<Map<String, dynamic>>>?
How would you do ?
First I initialise my variables:
Map<String, List<Map<String, dynamic>>>? test = {
[{'test': 'test'}]
}
Here I want to perform a deepcopy so I use jsonEncode jsonDecode which will clone my variable and cast my clone into a Map<dynamic>.
jsonDecode(jsonEncode(test))
Next I want to cast my result into a MapEntry<String, List<dynamic>>.
(jsonDecode(jsonEncode(test)) as Map).map((key, value) => MapEntry(key, value))
Finally I want to cast my value (List<dynamic>) into a List<Map<String, dynamic>>
Map<String, List<Map<String, dynamic>>>? result = (jsonDecode(jsonEncode(test)) as Map).map((key, value) =>
MapEntry(key, (value as List).map((e) => e as Map<String, dynamic>).toList())
Here the variable has now a type of: Map<String, List<Map<String, dynamic>>>?
So this is the answer for performing a deep copy with a deep casting.
I have an error when trying to convert a list of my object to json
My error:
Unhandled Exception: type 'RxList<ItemStockEntryModel>' is not a subtype of type 'Map<dynamic, dynamic>'
My model code:
class StockEntryModel {
final int? id;
final double costFreight;
final List<ItemStockEntryModel> items;
StockEntryModel({
this.id,
required this.costFreight,
required this.items,
});
factory StockEntryModel.fromJson(Map<String, dynamic> json) =>
StockEntryModel(
id: json['id'],
costFreight: json['costFreight'],
items: json['itemStockEntries'],
);
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items,
};
Map<String, dynamic> itemsToMap() => {
'data': items,
};
String itemsToJson() {
var data = {};
final test = itemsToMap()['data'];
final mappedItems = Map<String, dynamic>.from(test) // the error occurs here on test variable
..removeWhere((key, value) => value == null || key == 'product');
print(json.encode(mappedItems));
data['itemStockEntries'] = mappedItems;
return json.encode(data);
}
}
my goal is to return a json object like this
// is not complete, only example...
{
"itemStockEntries": {
"data": [{
"id": 2
}, {
"id": 3
}]
}
}
but i need remove keys if this value is null and my key product..
I saw some similar errors, but I couldn't find the one that actually causes it
sorry for my bad english =(
My solution based on Loren codes. I expect to help someone also
Map<String, dynamic> toJson() => {
'id': id,
'costFreight': costFreight,
'itemStockEntries': items.map((e) => e.toJson()).toList(),
};
Map<String, dynamic> itemsToMap() => {
'data': items
.map(
(e) => e.toJson()
..removeWhere(
(key, value) => key == 'product' || value == null),
)
.toList(),
};
Map<String, dynamic> modelToJson() {
Map<String, dynamic> data = {};
data['itemStockEntries'] = itemsToMap();
data['costFreight'] = costFreight;
print(json.encode(data));
return data;
}
The .from method on a map needs a map to be passed into it, and you're passing in a list. So removeWhere is looking for keys and values which don't exist the way you're doing it.
So you could clear that first error getting rid of the itemsToMap function and changing the first 2 lines of your itemsToJson function to this.
var data = {'data': items}; // an actual map that you can pass in
final mappedItems = Map<String, dynamic>.from(data) // no more error here
But that's still a map with just a single key with a value of a list. So the removeWhere is not going to do anything of value here.
The List<ItemStockEntryModel> is what you need to be iterating through.
Assuming you have json serialization setup in your ItemStockEntryModel, this is closer to what you need to do. Not a complete example because I don't know what that model looks like, but it should give you the idea.
String itemsToJson() {
Map data = {};
List<String> jsonList = []; // new list of json strings to pass into data map
for (final item in items) {
if (// item meets whatever conditions you need) {
final jsonItem = json.encode(item);
jsonList.add(jsonItem);
}
}
data['itemStockEntries'] = {'data': jsonList};
return json.encode(data);
}