Flutter - how to make an array of objects - list

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/

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

How To Display a Random Item of a List? [Every 9 seconds]

Is there a way to display a randomQuote every 9 seconds automatically?
Below is a truncated portion of the code that matters:
final List<String> RandomQuotes = [ ... ] // (one hundreds quotes here)
var randomQuote = (RandomQuotes.toList()..shuffle()).first;
:
:
:
... Text(randomQuote, Style:...)
I've tried your suggested code, but the randomQuote var is not being used. As seen in the images below.
Quite easy just use a Timer.periodic and define a duration of 9 seconds:
import 'dart:async';
import 'dart:math';
final items = <String>['Hi', 'Hello', 'Test'];
Timer.periodic(Duration(seconds: 9), (_) {
final _random = Random();
final item = items[_random.nextInt(items.length)];
print(item);
});
Try the full code on DartPad
Easiest solution in a single line:
final List<String> RandomQuotes = [ ... ] // (one hundreds quotes here)
Timer.periodic(Duration(seconds: 9), (_) {
var randomQuote = (RandomQuotes..shuffle()).first;
});

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 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

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