'Flutter Search bar not displaying all the users

I have been implementing a search bar in Flutter, which works as expected when searching according to usernames, but does not display all the users when it is empty.

It only displays all the users when typing something in the search bar and completely backspacing it. The following code snippet shows its implementation:

class UsersTable extends StatefulWidget {
  List<User> users;
  List<Library> posts;
  UsersTable(
    this.users,
    this.posts, {
    Key? key,
  }) : super(key: key);

  @override
  State<UsersTable> createState() => _UsersTableState();
}

class _UsersTableState extends State<UsersTable> {
  List<User> _foundUsers = [];

  @override
  initState() {
    // at the beginning, all users are shown
    Future.delayed(Duration.zero, () async {
      _foundUsers = widget.users;
      print(_foundUsers.length);
      if (mounted) setState(() {});
    });
    super.initState();
  }

  // This function is called whenever the text field changes
  void _runFilter(String enteredKeyword) {
    List<User> results = [];
    if (enteredKeyword.trim().isEmpty) {
      // if the search field is empty or only contains white-space, we'll display all users
      results = widget.users;
      print("if filter length");
      print(results.length);
    } else {
      results = widget.users
          .where((user) => user.username
              .toLowerCase()
              .contains(enteredKeyword.toLowerCase()))
          .toList();
      // we use the toLowerCase() method to make it case-insensitive
    }
    // Refresh the UI
    setState(() {
      _foundUsers = results;
    });
  }

  Widget body(BuildContext context, List<User> users, List<Library> posts) {
    return SafeArea(
        child: Material(
            child: Container(
      padding: const EdgeInsets.all(defaultPadding),
      decoration: const BoxDecoration(
        color: boxColor,
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          const Align(
              alignment: Alignment.center,
              child: Text(
                "Active Users",
                //style: Theme.of(context).textTheme.subtitle1,
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    decoration: TextDecoration.none),
              )),
          const SizedBox(
            height: 30,
          ),
          TextField(
            style: const TextStyle(color: Colors.white),
            onChanged: (value) => _runFilter(value),
            decoration: const InputDecoration(
                labelStyle: TextStyle(color: Colors.white38),
                labelText: 'Search',
                suffixIcon: Icon(Icons.search),
                suffixIconColor: Colors.white),
          ),
          const SizedBox(
            height: 20,
          ),
          // SizedBox(
          //width: double.infinity,
          // child: SingleChildScrollView(
          Container(
            child: DataTable(
                columnSpacing: 7,
                columns: const [
                  // DataColumn(
                  //   label: Text(
                  //     "First Name",
                  //     style: TextStyle(color: Colors.white),
                  //   ),
                  // ),
                  // DataColumn(
                  //   label: Text(
                  //     "Last Name",
                  //     style: TextStyle(color: Colors.white),
                  //   ),
                  // ),
                  DataColumn(
                    label: Text(
                      "Username",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      "Email ID",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  // DataColumn(
                  //   label: Text(
                  //     "DOB",
                  //     style: TextStyle(color: Colors.white),
                  //   ),
                  // ),
                  DataColumn(
                    label: Text(
                      "Account\nType",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      "Delete\nUser",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      "View\nPosts",
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
                rows:
                    //_foundUsers.isNotEmpty?
                    _foundUsers
                        .map(
                          (user) => DataRow(
                            cells: <DataCell>[
                              // DataCell(Text(user.first_name,
                              //     style: TextStyle(color: Colors.white))),
                              // DataCell(Text(user.last_name,
                              //     style: TextStyle(color: Colors.white))),
                              DataCell(Text(user.username,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(color: Colors.white))),
                              DataCell(Text(user.email,
                                  style: TextStyle(color: Colors.white))),
                              // DataCell(Text(user.date_of_birth,
                              //     style: TextStyle(color: Colors.white))),
                              DataCell(Text(user.account_type,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(color: Colors.white))),
                              DataCell(
                                ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    primary: Colors.purple,
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 15, vertical: 15),
                                    textStyle: const TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold),
                                    shadowColor: Colors.grey,
                                  ),
                                  onPressed: () {
                                    // if (user.username
                                    //         .compareTo('hwumazijadmin48') !=
                                    //     0) {
                                    BlocProvider.of<AuthenticationBloc>(context)
                                        .add(DeleteUser(
                                            username: user.username));
                                    // } else {
                                    //   const Text("Cannot Delete Admin");
                                    // }
                                  },
                                  child: const Text('X'),
                                ),
                              ),
                              DataCell(
                                ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    primary: Colors.purple,
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 15, vertical: 15),
                                    textStyle: const TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold),
                                    shadowColor: Colors.grey,
                                  ),
                                  onPressed: () {
                                    List<Library> po = [];
                                    int i = 0;
                                    while (i < posts.length) {
                                      if (posts[i]
                                              .user
                                              .compareTo(user.username) ==
                                          0) {
                                        po.add(posts[i]);
                                      }
                                      i++;
                                    }
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => PostsTable(po),
                                      ),
                                    );
                                  },
                                  child: const Text('\u{1F441}'),
                                ),
                              ),
                            ],
                          ),
                        )
                        .toList()
                //: []
                ),
          ),
          // ),
        ],
      ),
    )
            //)
            ));
  }

Am I missing something in the code?



Solution 1:[1]

move super.initState(); above and remove Future.delayed.

  @override
  initState() {
    super.initState();
    _foundUsers = widget.users;        
  }

no need to setState({}); because build method will trigger after initState. Also no need for mounted because we removed asyncoperation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Autocrab