How to Generate map from class - flutter

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());

Related

Map<dynamic, dynamic> returns null even though data is present

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

How to add items to the following lists?

I have a following list and I want to add new items to that list when I click a button. How to achieve it?
List<dynamic> list = [
{
'id': 0,
'leading': 'Payment Application',
'trailing': 'System',
},
{
'id': 1,
'leading': 'Reference Number',
'trailing': 'SYM12113OI',
},
{
'id': 2,
'leading': 'Total',
'trailing': '\$15.00',
},
{
'id': 3,
'leading': 'Details',
'trailing': 'Civil Employment',
},
];
Try the following code:
TextButton(
child: Text("child"),
onPressed: () {
list.add(value);
}
),
1st create a Model for Your List Object :
Example:
// To parse this JSON data, do
//
// final listModel = listModelFromJson(jsonString);
import 'dart:convert';
List<ListModel> listModelFromJson(String str) => List<ListModel>.from(json.decode(str).map((x) => ListModel.fromJson(x)));
String listModelToJson(List<ListModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ListModel {
ListModel({
this.id,
this.leading,
this.trailing,
});
int id;
String leading;
String trailing;
factory ListModel.fromJson(Map<String, dynamic> json) => ListModel(
id: json["id"],
leading: json["leading"],
trailing: json["trailing"],
);
Map<String, dynamic> toJson() => {
"id": id,
"leading": leading,
"trailing": trailing,
};
}
Now You can define your List Like this:
List<ListModel> _list = [];
For Add Data In your List you can do :
_list.add(ListModel(id:1022,leading:"leading name",trailing:"training part "));

How to convert String into List of dynamic in flutter

I am working on a flutter project with firebase.
When I tried to fetch data ({id: 2021-10-13 04:48:15.582, title: Red Shirt, quantity: 1, price: 29.99}, {id: 2021-10-13 04:48:19.438, title: Mobile Phone, quantity: 1, price: 215})
So, I want to convert each map to a list of dynamic because I got this error
Error: Expected a value of type 'List< dynamic>', but got one of type 'String'
here is my code to fetch data
Future<void> fetchandSetOrders() async {
const url = "https://test-app.firebaseio.com/orders.json";
final response = await http.get(Uri.parse(url));
final List<OrderItem> loadedOrders = [];
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
extractedData.forEach((orderId, orderData) {
print(orderData['products']);
print(orderData['products'].runtimeType);
loadedOrders.add(
OrderItem(
id: orderId,
amount: orderData['amount'],
dateTime: DateTime.parse(orderData['dateTime']),
products: (orderData['products'] as List<dynamic>)
.map(
(item) => CartItem(
id: item['id'],
price: item['price'],
quantity: item['quantity'],
title: item['title'],
),
)
.toList(),
),
);
});
_orders = loadedOrders.reversed.toList();
notifyListeners();}

Dynamic list not maping from json Data

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

Null value when retreived from a list map, but not null when printed as a string

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
}