Dynamic list not maping from json Data
var jsondata = [
{
'value': '1',
'label': 'Red',
},
{
'value': '2',
'label': 'Green',
},
{
'value': '3',
'label': 'Yellow',
},
];
List<Map<String, dynamic>> _items = jsondata;
JSON Data not maping as variable with List<Map<String, dynamic>>.
You can use json_serializabl to parse JSON.
The document of official can teach you to do this.
Sample code from the document of official
Map<String, dynamic> user = jsonDecode(jsonString);
print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');
Ref: https://flutter.dev/docs/development/data-and-backend/json
Related
I have a map which contains data. But the moment I do this map["content"] it tells me null. What is the problem.
This is the code
final messages = snap.data!.snapshot.value as Map<dynamic, dynamic>;
This is what I'm doing
messages["idFrom"]
messages is Map<dynamic, dynamic> or Map<int, dynamic> from your response
Map<int, dynamic> messages = {
1673561668839422: {
'timeStamp': 1673561668840253,
'idTo': 'hMKNXQxOHTSi6WqbuHN5uabQwea2',
'idFrom': '7BEeF0rHihfIFRvv9ClqIdAzzPP2',
'type': 0,
'content': 'Hi'
},
1673562395023337: {
'timeStamp': 1673562395023396,
'idTo': 'hMKNXQxOHTSi6WqbuHN5uabQwea2',
'idFrom': '7BEeF0rHihfIFRvv9ClqIdAzzPP2',
'type': 0,
'content': 'How are you'
},
...
};
You cannot do messages['idFrom'] because idFrom is a key from nested Map which is :
{
'timeStamp': 1673561668840253,
'idTo': 'hMKNXQxOHTSi6WqbuHN5uabQwea2',
'idFrom': '7BEeF0rHihfIFRvv9ClqIdAzzPP2',
'type': 0,
'content': 'Hi'
}
If you wanna access idFrom you can either do messages[int]['idFrom'] where int is one of the keys of messages Map.
ex.. print(messages[1673561668839422]['idFrom'])
7BEeF0rHihfIFRvv9ClqIdAzzPP2
I am using this code to upload data to firebase:
List<Map<String, dynamic>> mapData = [
{
'name': 'name1',
'done': false,
'frequency': '1',
},
{
'name': 'name2',
'done': false,
'frequency': '5',
},
];
if (isExist == false && listNameController.text.isNotEmpty) {
await Firestore.instance
.collection(widget.user.uid)
.document(listNameController.text.toString().trim())
.setData({
'users': mapData,
});
But now I want to add more data.
I have tried this code but it overwrites all content. What can I do to just add the data to 'users'?
Firestore.instance
.collection(widget.user.uid)
.document(widget.currentList.keys.elementAt(widget.i))
.updateData({
'users': {
'name': 'name3',
'done': false,
'frequency': '7'
},
You can use arrayUnion to add array elements. Please use latest version of firestore package from pub.dev
Firestore.instance
.collection(widget.user.uid)
.document(widget.currentList.keys.elementAt(widget.i)).update({
"users": FieldValue.arrayUnion([new User]),
});
Can't seem to find why the value is equal to null when in fact it isn't.
if I do a print(studioName); it will print the value retrieved from Firestore Database.
But when I try to retrieve it from the list, it will print as a null.
String studioName;
class Homne extends StatefulWidget {
#override
_HomneState createState() => _HomneState();
}
class _HomneState extends State<Homne> {
CollectionReference users = FirebaseFirestore.instance.collection('PopularPlacesList');
getPopularPlaces() async {
final snapShot = await FirebaseFirestore.instance
.collection('PopularPlacesList')
.doc('ksx1hVJn4Jf46ACFBbp7')
.get();
var data = snapShot.data();
studioName = data['name'];
}
var popularPlacesList = [
{
'name': '$studioName',
'image': 'assets/popular_places/miami.jpg',
'property': '783 properties'
},
{
'name': 'Singapore',
'image': 'assets/popular_places/singapore.jpg',
'property': '593 properties'
},
{
'name': 'New York',
'image': 'assets/popular_places/newyork.jpg',
'property': '1025 properties'
},
{
'name': 'Venice',
'image': 'assets/popular_places/venice.jpg',
'property': '290 properties'
},
{
'name': 'Vietnam',
'image': 'assets/popular_places/vietnam.jpg',
'property': '193 properties'
}
];
Where the code is presented in a list view builder:
Container(
width: width,
height: 150.0,
child: ListView.builder(
itemCount: popularPlacesList.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
var item = popularPlacesList[index];
popularPlacesList is initialized before getPopularPlaces has finished loading. One solution would be to set popularPlacesList via setState after you've finished loading your data from Firestore.
class _HomneState extends State<Homne> {
CollectionReference users = FirebaseFirestore.instance.collection('PopularPlacesList');
var popularPlacesList = [];
getPopularPlaces() async {
final snapShot = await FirebaseFirestore.instance
.collection('PopularPlacesList')
.doc('ksx1hVJn4Jf46ACFBbp7')
.get();
final data = snapShot.data();
final studioName = data['name'];
setState(() => popularPlacesList = [
{
'name': '$studioName',
'image': 'assets/popular_places/miami.jpg',
'property': '783 properties'
},
{
'name': 'Singapore',
'image': 'assets/popular_places/singapore.jpg',
'property': '593 properties'
},
{
'name': 'New York',
'image': 'assets/popular_places/newyork.jpg',
'property': '1025 properties'
},
{
'name': 'Venice',
'image': 'assets/popular_places/venice.jpg',
'property': '290 properties'
},
{
'name': 'Vietnam',
'image': 'assets/popular_places/vietnam.jpg',
'property': '193 properties'
}
]);
}
// Rest of your class
}
I have a List<Map<String, String>> like below
[
{ 'name': 'John', 'id': 'aa' },
{ 'name': 'Jane', 'id': 'bb' },
{ 'name': 'Lisa', 'id': 'cc' },
]
And, the ID list **List** as ['bb', 'aa']. By using the ID list, I want to return a new list ['Jane', 'John'] as **List _selectedList**.
I have tried to do it with the .**indexWhere**, however, I am stuck on the List where it has more than one value.
How can I return the List only with the name-value when there is more than one value to look for?
void main() {
var a = [
{ 'name': 'John', 'id': 'aa' },
{ 'name': 'Jane', 'id': 'bb' },
{ 'name': 'Lisa', 'id': 'cc' },
];
var b = ['bb', 'aa'];
var c = a.where((m) => b.contains(m['id'])).map((m) => m['name']);
print(c);
}
Result
(John, Jane)
Use a set to filter out the IDs efficiently.
var ids = ["aa", "cc"];
var idSet = Set<String>.from(ids);
var json = [
{ 'name': 'John', 'id': 'aa' },
{ 'name': 'Jane', 'id': 'bb' },
{ 'name': 'Lisa', 'id': 'cc' },
];
var _selectedList = json.where((data) => idSet.contains(data["id"]))
.map((data) => data["name"]).toList();
print(_selectedList);
Here, .where filters out the data where the ID matches one in the input list "IDs". Sets make the process efficient. Then, the resultant objects are passed to .map where the "name" field is extracted. Finally, the whole thing is converted into a list thus returning the list of names.
Output of the above code:
[John, Lisa]
I have an events class thats like this
MyEvents(id: 5a9c120ab3473,
title: "Event 1",
description: "",
image: "",
isDone false,
classDate: 2019-08-23 00:00:00.000)
I'm getting a list from a database but i cant figure out how to turn it into this format for a calendar package (there could be multiple events on each day)
Map<DateTime, List<Map<String, Object>>> _events2 = {
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 24): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2019, 8, 23): [
{'name': 'Event A', 'isDone': true},
],
};
I've tried this, not sure if I'm on the right track or totally lost
events.map((c) {
print(c.title);
item = {
c.classDate: [
{'name': c.title, 'isDone': true},
]
};
mainList.add(item);
}).toList();
You can add a method in your class like this:
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
data['description'] = this.description;
data['image'] = this.image;
data['isDone'] = this.isDone;
data['classDate'] = this.classDate;
return data;
}
Found this solution
turned out to be exactly what i needed
events.map((c) {
print(c.title);
item = {'name': c.title, 'isDone': true, "class_date": c.classDate};
mainList.add(item);
}).toList();
print("collection");
var c = Collection(mainList.toList());
var result = c
.groupBy$1((e) => e["class_date"],
(e) => {"name": e["name"], "isDone": e["isDone"]})
.toDictionary$1((e) => e.key, (e) => e.toList());