Let’s say I have a list like this:
final list = ["a", "a", "b", "a", "c"]
And I use
ListView.Builder(
itemCount: list.length,
shrinkWrap: true,
builder: (context, index){
return ListTile(
title: Text(list.index),
onTap:(){}
)
}
)
Is there a way I can filter the list so that it displays only the objects that only contain “a”?
2
Just use the List
‘s .where
method to filter out elements that only contain the string “a”:
final listWithOnlyA = myCurrentList.where((element) => element == "a").toList();
You can also use .contains:
final listWithOnlyA = list.where((element) => element.contains("a")).toList();
Using your example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
final list = ["a", "a", "b", "a", "c"];
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final listWithOnlyA = list.where((element) => element == "a").toList();
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: ListView.builder(
itemCount: listWithOnlyA.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(listWithOnlyA[index]),
);
},
),
),
);
}
}