Home > OS >  how to search in a map inside list dart flutter
how to search in a map inside list dart flutter

Time:09-21

*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 },]

CodePudding user response:

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"]}");
              },
            ),
          )
        ],
      ),
    );
  }
}

CodePudding user response:

try this:

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