简体   繁体   中英

how to search in a map inside list dart flutter

*i want to search to country from search field and the i want to get the information of that country * List<Map<String, Object>> data = [ { 'country': 'Afghanistan', 'population': 38928346, 'density': 60, 'land Area': 652860 }, { 'country': 'Albania', 'population': 2877797, 'density': 105, 'land Area': 27400 }, { 'country': 'Algeria', 'population': 43851044, 'density': 18, 'land Area': 2381740 },]

You can follow this widget. Also It would be better to use a model class

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final courtries = data.map((e) => e["country"]).toList();

  List<Map<String, Object>> resultSet = [];

  late final TextEditingController controller = TextEditingController()
    ..addListener(() {
      resultSet = data
          .where((e) => "${e['country']}"
              .toLowerCase()
              .contains(controller.text.toLowerCase()))
          .toList();
      setState(() {});
    });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextField(
            controller: controller,
          ),
          Expanded(
            child: ListView.builder(
              itemCount: resultSet.length,
              itemBuilder: (context, index) {
                return Text("${resultSet[index]["country"]}");
              },
            ),
          )
        ],
      ),
    );
  }
}

try this:

data.where(
      (final element) => (element)['country'].toString().contains('iran'),
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM