Home > Back-end >  Filter in Flutter (Dart)
Filter in Flutter (Dart)

Time:08-31

I want to search list item. for example, Item name is "Iphone 7 Plus" when i type iphone plus it shows empty Result but when i type iphone 7 it gives me that item. Can anyone help me how i get result on iphone plus

I am using this method:

List _getSuggestions(String query) { List matches = [];

matches.addAll(searchItemList);

matches.retainWhere((s) =>
    s.ItemName!.toLowerCase().contains(query.toLowerCase()) ||
    s.ItemCode!.toLowerCase().contains(query.toLowerCase()));
return matches;

}

enter image description hereenter image description here

CodePudding user response:

You have to split your query string to do want you want.

Check this code :

void main(List<String> args) {
  final data = 'iPhone 7 plus';
  var search = 'iphone plus 7';
  var match = true;

  for (var element in search.split(' ')) {
    match = match && data.toLowerCase().contains(element.toLowerCase());
  }

  print('match = $match');
}

CodePudding user response:

The logic will be

List<Item> _getSuggestions(String query) {
    matches.clear();
    matches = searchItemList.where((e) {
      return e.code.toLowerCase().contains(query.toLowerCase()) ||
          e.name.toLowerCase().contains(query.toLowerCase());
    }).toList();

    return matches;
  }

And show all item on empty list

onChanged: (value) {
  final resultSet = _getSuggestions(value);
  matches = resultSet.isEmpty ? searchItemList : resultSet;
  setState(() {});
},

Play with the widget.

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

  @override
  State<TestA> createState() => _TestAState();
}

class Item {
  final String name;
  final String code;

  Item({
    required this.name,
    required this.code,
  });
}

class _TestAState extends State<TestA> {
  final List<Item> searchItemList =
      List.generate(44, (index) => Item(name: "$index", code: "code $index"));

  List<Item> matches = [];

  List<Item> _getSuggestions(String query) {
    matches.clear();
    matches = searchItemList.where((e) {
      return e.code.toLowerCase().contains(query.toLowerCase()) ||
          e.name.toLowerCase().contains(query.toLowerCase());
    }).toList();

    return matches;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextField(
            onChanged: (value) {
              final resultSet = _getSuggestions(value);
              matches = resultSet.isEmpty ? searchItemList : resultSet;
              setState(() {});
            },
          ),
          Expanded(
              child: ListView.builder(
            itemCount: matches.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(matches[index].name),
              );
            },
          ))
        ],
      ),
    );
  }
}
  • Related