Flutter - how to make an array of List - list

class Transactions {
final String id;
final double amount;
final String date;
const Transactions({
#required this.id,
#required this.amount,
#required this.date,
});}
I am trying to ad a transaction to the current month . When the user adds a transaction based on the current moth is I would like to add that transaction to the array,e
so I want to make a list of list of Transactions
this is what i have tried :
List<List> _userTransactions = [
List<Transactions> jan= [];
List<Transactions> feb= [];
List<Transactions> mar= [];
List<Transactions> apr= [];
List<Transactions> may= [];
.....
];
it is giving me this error:
and I am also struggling trying to add to the list
I am not sure about the logic

To my mind, Map is more convenient choice, because you can set months as keys. It's like an associative array.
Map<int, List> _userTransactions = {
DateTime.january: [],
DateTime.february: [],
DateTime.march: [],
DateTime.april: [],
DateTime.may: [],
};
}

I think i know the answer.
You can try it like this:
List<List> _userTransactions = [
<Transactions>[],
<Transactions>[],
<Transactions>[],
<Transactions>[],
<Transactions>[],
.....
];
or if you want to reuse those widgets you can do it like this:
List<Transactions> jan= [];
List<Transactions> feb= [];
List<Transactions> mar= [];
List<Transactions> apr= [];
List<Transactions> may= [];
List<List> _userTransactions = [
jan,
feb,
mar,
apr,
may,
.....
];
Hope i've answered you. Happy coding:)

Use
List<List<Transactions>> _userTransactions=[
List<Transactions> jan= [];
List<Transactions> feb= [];
List<Transactions> mar= [];
List<Transactions> apr= [];
List<Transactions> may= [];
.....
];
That Should Work

Related

how to get value of item in array of list and make them independent list

I have list like example below, I want to get value of nameCategory and make them to List
List<Categories> iconCategory= [
Categories(
iconPath: 'assets/images/icons/IncomeIcon/001-salary.svg',
nameCategory: 'Salary',
),
Categories(
iconPath: 'assets/images/icons/IncomeIcon/002-interest.svg',
nameCategory: 'Interest',
),
Categories(
iconPath: 'assets/images/icons/IncomeIcon/003-award.svg',
nameCategory: 'Award',
)];
to list like example below but the data is from array list above
how I can do that
List<String> myCategory = ['Salary','Interest','Award'];
You can simply use the map method to achieve this:
List<String> myCategory = mycategories.map((e) => e.nameCategory).toList();
print(myCategory); // Prints [Salary, Interest, Award]
this will give you what you need
List<Categories> s1 = [];
List<String> ss = [];
result!.map((e) {
ss.add(e.nameCategory);
});

making sublists from a list and adding all sublists in one list in Flutter

Can anybody help me with list concepts?
I have a List of names and I want to make sublists of words with the same letter then add all those sublists in a list.
this is my code:
List<String> items = [
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten'
];
List<String> sublist;
#override
void initState() {
super.initState();
//----- sort alphabetically
items.sort((a, b) =>
a.toString().toLowerCase().compareTo(b.toString().toLowerCase()));
//----- get the initials
sublist = items.map((element) => element[0]).toList();
//----- remove duplicates
sublist = sublist.toSet().toList();
// ---------------- generate lists
List s = [];
List<List> listOfLists = [];
sublist.forEach((letter) async {
items.forEach((item) =>
item.startsWith(letter) ? s.add(item) : {items.iterator.moveNext()});
listOfLists.add(s);
print(letter);
print(s);
s.clear();
});
print(listOfLists);
this is what I want to get from listOfList : [ [eight], [five, four], [nine], [one], [seven, six], [ten, three, two] ]
but I just get empty sublists:
Here is my result: enter image description here
You are clearing the lists in each iteration.
Remove s.clear() and move List s = [] inside the for each function
// ---------------- generate lists
List<List> listOfLists = [];
sublist.forEach((letter) async {
List s = [];
items.forEach((item) => item.startsWith(letter) ? s.add(item) : {items.iterator.moveNext()});
listOfLists.add(s);
print(letter);
print(s);
});
Anyway, I would recommend you not to use forEach inside another forEach
You can then use:
List<List> listOfLists = [];
sublist.forEach((letter) async {
List s = items.where((item) => item.startsWith(letter)).toList();
listOfLists.add(s);
});

Flutter - how to make an array of objects

Edit:
class Transactions {
final String id;
final double amount;
final String date;
const Transactions({
#required this.id,
#required this.amount,
#required this.date,
});}
I am trying to ad a transaction to the current month . When the user adds a transaction based on the current moth is I would like to add that transaction to the array,e
so I want to make a list of list of Transactions
this is what i have tried :
List<List> _userTransactions = [
List<Transactions> jan= [];
List<Transactions> feb= [];
List<Transactions> mar= [];
List<Transactions> apr= [];
List<Transactions> may= [];
.....
];
Edit:
already answered
you might want try this one:
final grid = List<List<int>>.generate(
size, (i) => List<int>.generate(size, (j) => i * size + j));
If all you want is to initialize a list of hard-coded integers, you can do:
var list = [
[1, 2, 3],
[4, 5, 6]
];
You can specify the type instead of var if you want, it is List<List<int>>.
Or, if you want to generate a grid, you can either use a for loop with the add function, or use generate as per mra9776's answer.
Here we have a class with name as Transactions
So to make the list of Transactions objects we have to create list which is of type Transactions
In the below code part we created a List
of type Transactions and added objects to them by creating them with the help of new variable
List<Transactions> _userTransactions = [
new Transactions(100, 5000, "4-10-2020"),
new Transactions(101, 5000, "4-11-2020")
];
for more information about creation of objects and adding them to the List
please click the link https://kodeazy.com/flutter-array-userdefined-class-objects/

Search for Substring in several fields with MongoDB and Mongoose

I am so sorry, but after one day researching and trying all different combinations and npm packages, I am still not sure how to deal with the following task.
Setup:
MongoDB 2.6
Node.JS with Mongoose 4
I have a schema like so:
var trackingSchema = mongoose.Schema({
tracking_number: String,
zip_code: String,
courier: String,
user_id: Number,
created: { type: Date, default: Date.now },
international_shipment: { type: Boolean, default: false },
delivery_info: {
recipient: String,
street: String,
city: String
}
});
Now user gives me a search string, a rather an array of strings, which will be substrings of what I want to search:
var search = ['15323', 'julian', 'administ'];
Now I want to find those documents, where any of the fields tracking_number, zip_code, or these fields in delivery_info contain my search elements.
How should I do that? I get that there are indexes, but I probably need a compound index, or maybe a text index? And for search, I then can use RegEx, or the $text $search syntax?
The problem is that I have several strings to look for (my search), and several fields to look in. And due to one of those aspects, every approach failed for me at some point.
Your use case is a good fit for text search.
Define a text index on your schema over the searchable fields:
trackingSchema.index({
tracking_number: 'text',
zip_code: 'text',
'delivery_info.recipient': 'text',
'delivery_info.street': 'text',
'delivery_info.city': 'text'
}, {name: 'search'});
Join your search terms into a single string and execute the search using the $text query operator:
var search = ['15232', 'julian'];
Test.find({$text: {$search: search.join(' ')}}, function(err, docs) {...});
Even though this passes all your search values as a single string, this still performs a logical OR search of the values.
Why just dont try
var trackingSchema = mongoose.Schema({
tracking_number: String,
zip_code: String,
courier: String,
user_id: Number,
created: { type: Date, default: Date.now },
international_shipment: { type: Boolean, default: false },
delivery_info: {
recipient: String,
street: String,
city: String
}
});
var Tracking = mongoose.model('Tracking', trackingSchema );
var search = [ "word1", "word2", ...]
var results = []
for(var i=0; i<search.length; i++){
Tracking.find({$or : [
{ tracking_number : search[i]},
{zip_code: search[i]},
{courier: search[i]},
{delivery_info.recipient: search[i]},
{delivery_info.street: search[i]},
{delivery_info.city: search[i]}]
}).map(function(tracking){
//it will push every unique result to variable results
if(results.indexOf(tracking)<0) results.push(tracking);
});
Okay, I came up with this.
My schema now has an extra field search with an array of all my searchable fields:
var trackingSchema = mongoose.Schema({
...
search: [String]
});
With a pre-save hook, I populate this field:
trackingSchema.pre('save', function(next) {
this.search = [ this.tracking_number ];
var searchIfAvailable = [
this.zip_code,
this.delivery_info.recipient,
this.delivery_info.street,
this.delivery_info.city
];
for (var i = 0; i < searchIfAvailable.length; i++) {
if (!validator.isNull(searchIfAvailable[i])) {
this.search.push(searchIfAvailable[i].toLowerCase());
}
}
next();
});
In the hope of improving performance, I also index that field (also the user_id as I limit search results by that):
trackingSchema.index({ search: 1 });
trackingSchema.index({ user_id: 1 });
Now, when searching I first list all substrings I want to look for in an array:
var andArray = [];
var searchTerms = searchRequest.split(" ");
searchTerms.forEach(function(searchTerm) {
andArray.push({
search: { $regex: searchTerm, $options: 'i'
}
});
});
I use this array in my find() and chain it with an $and:
Tracking.
find({ $and: andArray }).
where('user_id').equals(userId).
limit(pageSize).
skip(pageSize * page).
exec(function(err, docs) {
// hooray!
});
This works.

Lists AS value of a Map in Dart

I want to create a map of members, but every membres have 3 propreties : first name, last name, and username. How can I create like a list of liste, but with a map.
So I want to have something like :
var membres= {['lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'],
['lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'],
};
As you know, this code doesn't work. But it explain pretty well what I am trying to do.
I think you are confusing the two constructs here.
Read this introduction to the language: http://www.dartlang.org/docs/dart-up-and-running/ch02.html#lists
A list is a list of elements which can be denoted with the shorthand [...] syntax:
var list = [1, 2, "foo", 3, new Date.now(), 4];
Whereas a map can be denoted with the curly brace shorthand syntax:
var gifts = { // A map literal
// Keys Values
'first' : 'partridge',
'second' : 'turtledoves',
'fifth' : 'golden rings'
};
So, let's modify your code to work:
var members = [
{
'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'
},
{
'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'
}
];
You can, for example, print the information like this:
members.forEach((e) {
print(e['firstname']);
});
If I understand your intent correctly, you want to have a list of maps. What you have is correct except you confused [ and {. The following works:
var membres = [
{'lastname': 'Bonneau',
'firstname': 'Pierre',
'username': 'mariobross'},
{'lastname': 'Hamel',
'firstname': 'Alex',
'username': 'Queenlatifa'}
];
As an example, to get a list of all usernames:
print(membres.map((v) => v['username']));
If you don't really need a Map, what about using a class to improve the structure of your code :
class Member {
String firstname;
String lastname;
String username;
Member(this.firstname, this.lastname, this.username);
}
main() {
final members = new List<Member>();
members.add(new Member('Pierre', 'Bonneau', 'mariobross'));
members.add(new Member('Alex', 'Hamel', 'Queenlatifa'));
// use members
}
You mean like this?
// FirstName => LastName => Value
var lookup = new Map<String, Map<String, String>>();
// get / set values like this
void setValue(String firstName, String lastName, String value) {
if (!lookUp.containsKey(firstName))
lookUp[firstName] = new Map<String, String>();
lookUp[firstName][lastName] = value;
}
String getValue(String firstName, String lastName) {
if (!lookUp.containsKey(firstName)) return "";
return lookUp[firstName][lastName];
}
First of all you need to create a map with value as list. Dont forget to initialize it
then if you want to fill it you first need to use built in function like putIfAbsent as in dart to add first object in list and then use update to add items in list. therefore you will need two arrays. First to put elements and then to add elements in list with same key. Also you can use try catch to identify if the key is present or not to do that in one loop
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.putIfAbsent(
date_time,
() => [
{
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
}
]);
}
for (var item in days) {
var date_time = DateTime.parse(item["date"] + " 00:00:00");
_events[date_time] = _events.update(date_time, (value) {
value.add({
"title": item["title"],
"date": item["date"],
"time": reUse.get_time_am_pm_format(item["time"]),
"feature": item["feature"],
});
return value;
});
}