Update List Single or Unique Item using Dart

Update List Single or Unique Item using Dart :

List type dart :

  • Fixed-length list (list’s length cannot be changed)
List<String>fixedList = List<String>(3);
  • Growable list (size can be changed to accommodate new items or remove items)
List<int>growableList = List<int>();
  • Dart List is an ordered collection which maintains the insertion order of the items.
  • Dart List allows duplicates and null values. For example: growableList.add(null);

Dart/Flutter initialize List with values :

  • Initialize list in simple way using operator [].
  • Create and fill a list with specified value using filled() constructor.
  • Create a list containing all specified itemsusingfrom() constructor.
  • Create a ‘const’ list using unmodifiable() constructor.
  • Create and fill a list with values by a generator function using generate() constructor.
List<int>intList = [1, 2, 3];

Combine Lists :

  • from() and addAll() method
  • expand() method
  • operator +
  • spread operator … or null-aware spread operator …? (from Dart 2.3)
var list1 = [1, 2, 3];
var list2 = [4, 5];
var list3 = [6, 7, 8];

// from() and addAll() method
var combinedList1= List.from(list1)..addAll(list2)..addAll(list3);

// expand() method
var combinedList2 = [list1, list2, list3].expand((x) => x).toList();

// operator +
var combinedList3  = list1 + list2 + list3;

// spread operator
var combinedList4 = [...list1, ...list2, ...list3];

Iterate over List in Dart :

  • forEach() and lambda expression.
  • iterator property to get Iterator that allows iterating.
  • every() method
  • simple for-each loop
  • for loop with item index
varmyList=[0,'one','two','three','four','five'];

// use forEach()
myList.forEach((item)=>print(item));
// or
myList.forEach(print);

// use iterator
varlistIterator=myList.iterator;
while(listIterator.moveNext()){
print(listIterator.current);
}

// use every()
myList.every((item){
print(item);
returntrue;
});

// simple for-each
for(var item inmyList){
print(item);
}

// for loop with item index
for(vari=0;i<myList.length;i++){
print(myList[i]);
}

Filter items for a List in Dart :

  • filter all items in List that matche the condition | where()
  • get the first item in List that matches the condition | firstWhere()
  • get the last item in List that matches the condition | lastWhere()
varmyList=[0,2,4,6,8,2,7];
myList.where((item)=> item >5).toList();// [6, 8, 7]
myList.firstWhere((item)=> item >5);// 6
myList.lastWhere((item)=> item >5);// 7
void main() {
  List<double> prices = [0.25, 1.00, 3.33, 0.75, 4.25, 5.99];  
varoverOneDollar = prices.where((p) => p > 1.00);
  log(overOneDollar); //prints 3.33, 4.25, 5.99
}

void log(varlst) {
lst.forEach((n) => print(n));
}

List map items into new List :

  • Dart List to new form using map()
varmyList=['zero','one','two','three','four','five'];
var uppers =myList.map((item)=>item.toUpperCase()).toList();
/*
myList: [zero, one, two, three, four, five]
uppers: [ZERO, ONE, TWO, THREE, FOUR, FIVE]
*/

User defined objects List in Dart :

classCustomer{
  String name;
int age;

Customer(this.name,this.age);

@override
  String toString(){
return'{ ${this.name}, ${this.age} }';
}
}

main(){
  List customers =[];
customers.add(Customer('Jack',23));
customers.add(Customer('Adam',27));
customers.add(Customer('Katherin',25));

print(customers);
print(customers.length);
}

Sort a List of objects in Dart/Flutter :

List Sort :

List<String> numbers = ['Java', 'Flutter', 'C'];
numbers.sort((a, b) =>a.length.compareTo(b.length));
print(numbers);  

List Sort by length :

List<String> numbers = ['Java', 'Flutter', 'C', 'C++'];  
numbers.sort((a, b) =>a.length.compareTo(b.length));
print(numbers); 

List Join or Comma separed value get in flutter or dart :

List<String> list = ['a', 'b', 'c'];
list.join(', ');

List remove data specific :

List<String> parts = ['head', 'shoulders', 'knees', 'toes'];
parts.remove('head');
print(parts); 

List remove all objects :

List<String> numbers = ['one', 'two', 'three', 'four'];
numbers.removeWhere((item) =>item.length == 3);
classCustomer{
  String name;
int age;

Customer(this.name,this.age);

@override
  String toString(){
return'{ ${this.name}, ${this.age} }';
}
}

main(){
  List customers =[];
customers.add(Customer('Jack',23));
customers.add(Customer('Adam',27));
customers.add(Customer('Katherin',25));

customers.sort((a, b)=>a.age.compareTo(b.age));
print('Sort by Age: '+customers.toString());

customers.sort((a, b)=>a.name.compareTo(b.name));
print('Sort by Name: '+customers.toString());
}
classCustomerextendsComparable{
  String name;
int age;

Customer(this.name,this.age);

@override
  String toString(){
return'{ ${this.name}, ${this.age} }';
}

// sort by Name (asc), then age (desc)
@override
intcompareTo(other){
intnameComp=this.name.compareTo(other.name);
if(nameComp==0){
return-this.age.compareTo(other.age);// '-' for descending
}
returnnameComp;
}
}

main(){
 List customers =[];
customers.add(Customer('Jack',23));
customers.add(Customer('Adam',27));
customers.add(Customer('Katherin',25));
customers.add(Customer('Jack',32));

customers.sort();
print(customers);
}

Mapping :

  • Mapping allows you to take a List and transform it into something else.
class Person
{
  String firstName;
  String lastName;

  Person(this.firstName, this.lastName);
}

void main() {
  List<Person> people = new List<Person>();
people.add(new Person("Kamlesh", "Lakhani"));
people.add(new Person("Patrick", "Thomas"));
varmappedNames = people.map((n) =>'Mr. ${n.firstName} ${n.lastName}');
  log(mappedNames);
}

void log(vardata) {
data.forEach((n) => print(n));
}

output
Mr. Kamlesh Lakhani
Mr. Patrick Thomas
class Sale {
intemployeeId;
  double price;
  Sale(this.employeeId, this.price);
}

class Employee {
intid;
  List<Sale>sales;
  Employee(this.id, this.sales);
}

void main() {
  List<Employee> employees = new List<Employee>();
employees.add(new Employee(1, [new Sale(1, 100.50), new Sale(1, 300.25)]));
employees.add(new Employee(2, [new Sale(2, 300.00), new Sale(2, 50.25), new Sale(2, 150.00)]));
employees.add(new Employee(3, [new Sale(2, 400.00), new Sale(2, 30.75), new Sale(3, 50.00)]));

employees.sort((a, b) => (b.sales.fold(0, (prev, element) =>prev + element.price)).compareTo(a.sales.fold(0, (prev, element) =>prev + element.price)));
  log(employees); 
}

void log(vardata) {
data.forEach((l) => print(
"Employee ${l.id} has ${l.sales.length} sales totaling ${l.sales.fold(0, (prev, element) =>prev + element.price)} dollars!"));
}

output
Employee 2 has 3 sales totaling 500.25 dollars!
Employee 3 has 3 sales totaling 480.75 dollars!
Employee 1 has 2 sales totaling 400.75 dollars!

main() {
  List<UserData> str = new List();
  str.add(UserData(1, 'Hiren'));
  str.add(UserData(2, 'Nayan'));
  str.add(UserData(3, 'Hirva'));
  str.add(UserData(4, 'kamlesh'));

  int id = str.indexWhere((note) => note.id == 3);
  str[id].name = 'JayShree';

  print(str[id].name);
}

class UserData {
  int id;
  String name;
  UserData(this.id, this.name);
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in