Home > Software engineering >  Message when silver list is empty
Message when silver list is empty

Time:01-11

How to show a message when SilverList is empty? I am trying to filter a list of users using SliverList and SliverChildBuilderDelegate. When I type some filter it returns empty screen, I want to show some message. Here is my code

  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder<UsersCubit, UsersState>(builder: (context, userState) {
        if (userState is UsersLoaded) {
          List<UserEntity> allUsers = userState.users
              .where((user) =>
                  user.name!.contains(_searchController.text.toLowerCase()))
              .toList();

          return CustomScrollView(
            slivers: <Widget>[
              SliverAppBar(
                floating: true,
                snap: true,
                automaticallyImplyLeading: false,
                elevation: 0,
                title: TextField(
                  controller: _searchController,
                  style: Theme.of(context).textTheme.bodyText1,
                  decoration: InputDecoration(
                    hintText: 'Search ...',
                  ),
                ),
              ),
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return User(
                      otherUser: allUsers[index],
                    );
                  },
                  childCount: allUsers.length,
                ),
              ),
            ],
          );
        } else {
          return const Scaffold(
              body: Center(child: CircularProgressIndicator()));
        }
      }),
    );
  }

CodePudding user response:

Check the length of allUsers list and if it is empty return widget that shows message, otherwise return SliverList.

List<UserEntity> allUsers = userState.users
    .where((user) =>
        user.name!.contains(_searchController.text.toLowerCase()))
    .toList();

return CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(
      floating: true,
      snap: true,
      automaticallyImplyLeading: false,
      elevation: 0,
      title: TextField(
        controller: _searchController,
        style: Theme.of(context).textTheme.bodyText1,
        decoration: InputDecoration(
          hintText: 'Search ...',
        ),
      ),
    ),
    if (allUsers.isEmpty) ...[
      SliverToBoxAdapter( 
          child: Container(
            // child widget to show when users is empty
          ),
      )
    ] else ...[
      SliverList(
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return User(
              otherUser: allUsers[index],
            );
          },
          childCount: allUsers.length,
        ),
      ),
    ],
  ],
);
  • Related