Yousef
Yousef

Reputation: 1

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

Upvotes: 0

Views: 382

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63604

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

Upvotes: 1

amin jamali
amin jamali

Reputation: 440

try this:

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

Upvotes: 0

Related Questions