i want to get StockModel which is code is "A006400" from below List.
const allStocks = [
StockModel(name: "대주주", code: "000000", count: 10000000),
StockModel(name: "삼성SDI", code: "A006400", count: 5000),
StockModel(name: "성일하이텍", code: "A365340", count: 300),
StockModel(name: "일진머티리얼즈", code: "A020150", count: 10),
StockModel(name: "하이트진로", code: "A000080", count: 1),
];
this is my function.
void setStock(String query) {
StockModel stockModel = allStocks.where((stock){
final stockCode = stock.code;
if(stockCode == query) {
return stock;
}
})
CodePudding user response:
You can do it like `
void setStock(String query) {
StockModel stockModel = allStocks.firstWhere((s) => s.code == query);
}
To get multiple items
final stockModels = allStocks
.where(
(element) => element.code == query,
)
.toList();
CodePudding user response:
Assuming the code field is unique across your objects, you can do:
void setStock(String query) {
StockModel stockModel = allStocks.singleWhere((stock) => stock.code == query);
}
CodePudding user response:
To get ALL item, use where, dart executable example:
class StockModel {
String? name;
String? code;
int? count;
StockModel({this.name, this.code, this.count});
}
List<StockModel> allStocks = [
StockModel(name: "대주주", code: "000000", count: 10000000),
StockModel(name: "삼성SDI", code: "A006400", count: 5000),
StockModel(name: "성일하이텍", code: "A365340", count: 300),
StockModel(name: "일진머티리얼즈", code: "A020150", count: 10),
StockModel(name: "하이트진로", code: "A000080", count: 1),
];
void setStock(String query) {
List<StockModel> stockModel = allStocks.where((stock) {
print(stock.code);
if (stock.code == query) {
return true;
}
return false;
}).toList();
print(stockModel.length.toString());
print(stockModel[0].code.toString());
}
main() {
setStock("A006400");
}