Home > Software engineering >  How to pull a single data from Flutter's object array list
How to pull a single data from Flutter's object array list

Time:11-06

I'm sorry if this is a very dumb question but I'm wondering how to pull a single data from flutter's object array list

My code

class Bank {
  late String name;
  late String nameBank;

  Bank({required this.name, required this.nameBank});
}

void main() {
  var bankMap = listBank.map((d) {
    return {"name": d.name};
  }).toList();
  print(bankMap);
}

List listBank = [
  Bank(name: 'Bank 1', nameBank: 'Bank 1'),
  Bank(name: 'Bank 2', nameBank: 'Bank 2')
];

I want to pull name: 'Bank 1' only. Thank you!

I tried adding [] like normal array but got an error

CodePudding user response:

First check the existence of this element to avoid errors

you need to make a loop and check whether if the value you need in list or not

            listBank.forEach((element) {
                          
                          if(element == 'DATA YOU WANT'){
                            // YOUR CODE HERE
                          }
                          
                        });

another way to do this is to check if array contains a specific element

listBank.contains(element);

use like

if (ordersWidgets.contains(element)){

// Array contains that value }

now get your value

   listBank.forEach((element) {
                          
                          if(element == 'DATA YOU WANT'){
                            var p = listBank[listBank.indexOf(element)];
                          }
                          
                        });

CodePudding user response:

To find only one element based on some condition.

var bank1 = listBank.firstWhere((bank) => bank.name == 'Bank 1');

Note that it throws an error if no elements match.

CodePudding user response:

Found another solution by using

class Bank {
  late String name;
  late String nameBank;

  Bank({required this.name, required this.nameBank});
}

void main() {
  Iterable visibleNames = listBank.where((nama) {
    return nama.nameBank.contains('Bank A');
  });
  visibleNames.forEach((nama) => print(nama.name));
}

// Need 'Iterable visibleNames' to see the data or the data won't print

// Iterable variable = listVar.where((newVar) {
//    return newVar.getterInListVar.contains('whatWeWantToSearch');
//  });

List listBank = [
  Bank(name: 'Bank 1', nameBank: 'Bank A'),
  Bank(name: 'Bank 2', nameBank: 'Bank B')
];

Explanation https://www.youtube.com/watch?v=y-sfrhq8Q_I

Thank you everyone!

  • Related