Ad

The Return Type 'dynamic' Isn't A 'bool', As Required By The Closure's Context

- 1 answer

I am implementing search bar in my flutter app. But the line _allUsers.where((user) => user["name"].toLowerCase().contains(enteredKeyword.toLowerCase())).toList(); throws an error: 'The return type 'dynamic' isn't a 'bool', as required by the closure's context.' There is code:

  final List<Map<String, dynamic>> _allUsers = [
    {"id": 1, "name": "Andy", "type": "student"},
    {"id": 2, "name": "Aragon", "type": "student"},
    {"id": 3, "name": "Bob", "type": "student"},
    {"id": 4, "name": "Barbara", "type": "teacher"},
    {"id": 5, "name": "Candy", "type": 'student'},
  ];
  void _runFilter(String enteredKeyword) {
    List<Map<String, dynamic>> results = [];
    if (enteredKeyword.isEmpty) {
      results = _allUsers;
    } else {
      results = _allUsers.where((user) => user["name"].toLowerCase().contains(enteredKeyword.toLowerCase())).toList();
    }
  }

When I try run this code in dartpad.dev it works, but in Android Studio it doesn't.

Ad

Answer

Try add a cast when you get the value from the map. Right now, the type is dynamic (because the map has been declared in such a way) which means type safety is thrown away:

  void _runFilter(String enteredKeyword) {
    List<Map<String, dynamic>> results = [];
    if (enteredKeyword.isEmpty) {
      results = _allUsers;
    } else {
      results = _allUsers
          .where((user) => (user["name"] as String)
              .toLowerCase()
              .contains(enteredKeyword.toLowerCase()))
          .toList();
    }
  }
Ad
source: stackoverflow.com
Ad