I want to add datas I pull from firebase.I store my data in sting clases . I want to pull that data from firebase. and add to local map list so I can acces quickly and easly.
` dynamic getData(Map data, List<String> way) {
dynamic dataTemp = data;
if (way.length > 0) {
for (int x=0; x < way.length; x++) {
dataTemp = dataTemp[way[x]];
}
}
return dataTemp;
}
List<Map<String, dynamic>> locations = [
{
'country': 'Japan',
'city': 'Tokyo',
'Latitude': 35.6762,
'Longitude': 139.6503,
'utcOffset': 9,
'example' : {
'data' : "text",
'number' : 20,
'boolean': false
}
}
];
getData(locations[0],["example","number"]);`
in this example how can I add multiple of .
` {
'country': 'Japan',
'city': 'Tokyo',
'Latitude': 35.6762,
'Longitude': 139.6503,
'utcOffset': 9,
'example' : {
'data' : "text",
'number' : 20,
'boolean': false
}
}`
this code
from my firebase database ?
Use .asMap()
Example:
List mylist = [];
mylist.add(locations);
final myMap = mylist.asMap();
print(myMap[0][0]['example']); // {data: text, number: 20,boolean: false}
print(myMap[0][0]['example']['number']); // 20
Related
I Have created a method that converts TransactionList to MapList for report of daily income and daily expenses..
output like
[
{
'date':28-01-23,
'totalIncome':300.00,
'totalExpense':300.00,
'balance':0.00,
},
{
....
},
]
here are the data of Transaction
List<Transaction> transactions=[
Transaction(date: DateTime(2023,01,18), isExpense: true, amount: 100.00,),
Transaction(date: DateTime(2023,01,18), isExpense: true, amount: 200.00,),
Transaction(date: DateTime(2023,01,18), isExpense: false, amount: 300.00,),
Transaction(date: DateTime(2023,01,19), isExpense: false, amount: 200.00,),
Transaction(date: DateTime(2023,01,19), isExpense: false, amount: 100.00,),
];
My method is working well but I think it is not proper coding, so I want to implement this method with some advance way....
List<Map<String, dynamic>> dailyreport() {
//grouping data based on date field of transactions
var maplist = groupBy(transactions, (Transaction element) => element.date);
List<Map<String, dynamic>> reportlist = [];
//loop for each key
for (var x in maplist.keys) {
double sum_expenses = 0;
double sum_income = 0;
//getting transaction based on key value
List<Transaction> trans = maplist[x] as List<Transaction>;
for (int i = 0; i < trans.length; i++) {
if (trans[i].isExpense)
sum_expenses = sum_expenses + trans[i].amount;
else
sum_income = sum_income + trans[i].amount;
}
//adding map to reportlist
reportlist.add({
'date': x,
'expenses': sum_expenses,
'income': sum_income,
'balance': sum_income - sum_expenses,
});
}
return reportlist;
}
Here's another approach, also using groupBy as you were, and then folding the resulting list values:
Map<String, dynamic> emptyReport(DateTime d) =>
{
"date": d,
"expenses": 0.0,
"income": 0.0,
"balance": 0.0,
};
Map<String, dynamic> addToReport(Map<String, dynamic> report, Transaction t) => report["date"] == t.date ?
{
...report,
if (t.isExpense)
...{
"expenses": t.amount + report["expenses"],
"balance": report["balance"] - t.amount,
}
else
...{
"income": t.amount + report["income"],
"balance": report["balance"] + t.amount,
}
} :
report; // or handle the case the dates don't match however you want. but that shouldn't happen the way it is used below
List<Map<String, dynamic>> dailyreport(List<Transaction> transactions) =>
groupBy(transactions, (t) => t.date).map((date, ts) => MapEntry(
date,
ts.fold(
emptyReport(date),
addToReport
))).values.toList();
Here's a try with one loop:
List<Map<String, dynamic>> dailyreport(List<Transaction> transactions) {
Map<DateTime, Map<String, dynamic>> resultsByDate = {};
for(var t in transactions) {
var curr = resultsByDate[t.date] ?? {
"date": t.date,
"expenses": 0.0,
"income": 0.0,
"balance": 0.0,
};
resultsByDate[t.date] = {
...curr,
if (t.isExpense)
...{
"expenses": t.amount + curr["expenses"],
"balance": curr["balance"] - t.amount,
}
else
...{
"income": t.amount + curr["income"],
"balance": curr["balance"] + t.amount,
},
};
}
return resultsByDate.values.toList();
}
I have customer collection inside I have list of merchant data like
{
'customer':'xyz',
'contactNumber':'999999999',
'merchantMap':[
{
'merchantName':'abx',
'merchantId':'dsdfsbdmmm'
},
{'merchantName':'abx',
'merchantId':'dsdfsbdmmm'
}
]
}
Here inside merchantMap I want to update his name by checking his merchantId.
How can I achieve this?
Lets assume your customer data is this:
var customerData = {
'customer': 'xyz',
'contactNumber': '999999999',
'merchantMap': [
{'merchantName': 'abx', 'merchantId': '12'},
{'merchantName': 'abx', 'merchantId': '23'}
]
};
and your specific id is this:
String selectedId = "23";
you can do this to change the item that contains that id:
var newMerchantMap =
(customerData["merchantMap"] as List<Map<String, dynamic>>)
.map((e) => e['merchantId'] == selectedId
? {'merchantName': 'newNAme', 'merchantId': e["merchantId"]}
: e)
.toList();
customerData['merchantMap'] = newMerchantMap;
result :
{
customer: xyz,
contactNumber: 999999999,
merchantMap: [
{merchantName: abx, merchantId: 12},
{merchantName: newNAme, merchantId: 23}
]
}
I have a list of map and I want to get the map of specific key
for example :
video of letter a
List<Map<String, String>> letters = const [
{
'letter': 'a',
'name' : 'ddd',
'video' : 'ss',
},
{
'letter': 'b',
'name' : 'ddd',
'video' : 'ss',
},
{
'letter': 'c,
'name' : 'ddd',
'video' : 'ss',
},
]
I guess you can use .where method like this
List listWithVideo = letters.where((element) => element['letter'] == 'a').toList();
Now here you will get list of maps where you will find your letter a.
If you want to get only one map or the first map that has the same, you can also use firstWhere method.
I am also beginner,but here is my effort
void main() {
List<Map<String, String>> letters = const [
{
'letter': 'a',
'name': 'ddd',
'video': 'ss',
}
,
{
'letter': 'b',
'name' : 'ddd',
'video' : 'ss',
},
{
'letter': 'c',
'name' : 'ddd',
'video' : 'ss',
},
];
Map<String,dynamic> lst=letters.firstWhere((element) {
return element['letter']=='a';
});
print(lst['video']);
}
its showing correct output
Try this:
Map<String, dynamic> getAMap() {
var list = letters.where((element) => element["letter"] == "a").toList();
return list.isNotEmpty ? list.first : {};
}
I found a way to do this , so i can use the index and get the data that i want from the map
int search (String letter){
int index=0;
for ( var i=0 ; i<list.length;i++ )
{
if (list[i]['letter']==letter){
index=i;
}
}
return index;
}
How can I print out only the lnames from the JSON list? The code below is an example.
void main() {
// int index = 0;
List sample = [
{
'fname': 'sellerA',
'lname': 'bola',
'companyName': 'Faithtuts',
'country': 'Nigeria',
},
{
'fname': 'sellerB',
'lname': 'abbey',
'companyName': 'Xerox',
'country': 'Dubai',
},
{
'fname': 'sellerC',
'lname': 'grace',
'companyName': 'Nebrob',
'country': 'Japan',
},
];
for(int index = 0; index < sample.length; index++){
var getCName = sample.map((e) => sample[index]['lname']);
print('$getCName');
}
}
The Result:
(bola, bola, bola)
(abbey, abbey, abbey)
(grace, grace, grace)
But I am looking to get something like this instead. (bola, abbey, grace)
By combining your for loop with map, you are iterating twice on your list.
Instead, try this:
for(int index = 0; index < sample.length; index++) {
var getCName = sample[index]['lname'];
print('$getCName');
}
Or:
for(final element in sample) {
var getCName = element['lname'];
print(getCName);
}
Or, simply:
sample.map((element) => element['lname']).forEach(print);
Full example
void main() {
List sample = [
{
'fname': 'sellerA',
'lname': 'bola',
'companyName': 'Faithtuts',
'country': 'Nigeria',
},
{
'fname': 'sellerB',
'lname': 'abbey',
'companyName': 'Xerox',
'country': 'Dubai',
},
{
'fname': 'sellerC',
'lname': 'grace',
'companyName': 'Nebrob',
'country': 'Japan',
},
];
sample.map((element) => element['lname']).forEach(print);
}
This prints the following to the console:
bola
abbey
grace
I'm using sembast in a flutter app, I have a getAll() function that looks like the following:
Future getFavorites() async {
List favSnapshot = await _favFolder.find(await _db);
if (favSnapshot.length > 0) {
return favSnapshot;
} else {
return null;
}
}
and it returns the following:
[
Record(favorites, 1) {hello: worls},
Record(favorites, 2) {name: Daredevil, season: 1, episode: 3},
Record(favorites, 3) {name: Daredevil, season: 1, episode: 2},
Record(favorites, 4) {name: Daredevil, season: 3, episode: 2},
Record(favorites, 5) {name: Daredevil, season: 1, episode: 13},
Record(favorites, 6) {name: Daredevil, season: 1, episode: 1}]
How can I check if I have {name: Daredevil, season: 1, episode: 13} in my data?
I can think of 2 ways to create a filter that checks whether a record "contains" some data.
You can combine filters:
/// Filter record that contains the same field (i.e. check multiple fields value)
Filter containsMapFilter(Map<String, Object?> map) {
return Filter.and(
map.entries.map((e) => Filter.equals(e.key, e.value)).toList());
}
var snapshots = await store.find(db,
finder: Finder(
filter: containsMapFilter(
{'name': 'Daredevil', 'season': 1, 'episode': 13})));
You can use a custom filter:
/// Filter record that contains the same field (i.e. check multiple fields value)
Filter containsMapFilter(Map<String, Object?> map) {
return Filter.custom((record) {
var data = record.value as Map;
for (var entry in map.entries) {
if (data[entry.key] != entry.value) {
return false;
}
}
return true;
});
}
var snapshots = await store.find(db,
finder: Finder(
filter: containsMapFilter(
{'name': 'Daredevil', 'season': 1, 'episode': 13})));
If you are looking for an exact match you can use a custom filter and the DeepCollectionEquality from the collection package:
// import 'package:collection/collection.dart';
/// Filter record that contains the same field (i.e. check multiple fields value)
Filter mapEqualsFilter(Map<String, Object?> map) {
return Filter.custom((record) {
var data = record.value as Map;
return DeepCollectionEquality().equals(map, data);
});
}
var snapshots = await store.find(db,
finder: Finder(
filter: mapEqualsFilter(
{'name': 'Daredevil', 'season': 1, 'episode': 13})));