简体   繁体   中英

SearchDelegate returns “true” to screen when click to search button

When I search for users in my application, I pull out and filter the users in the Firestore. After that, I show it as a list on the screen. But when you press the search button, it says "true" in the middle of the screen, the names are not displayed. What's wrong?

locator.dart

  getIt.registerLazySingleton(() => ProfileService());

  getIt.registerFactory(() => UserModel());

Profile.dart

class Profile {
  String userId;
  String name;
  String city;
  String email;
  int level;
  int phone;
  String image;
  String quest;
  int numberofbooks;
  int numberoflessons;
  int numberofnotes;
  Timestamp birthday;
  Timestamp signUpdate;
  String registeredby;

  Profile(
      {this.userId,
      this.name,
      this.city,
      this.email,
      this.level,
      this.phone,
      this.image,
      this.quest,
      this.numberofbooks,
      this.numberofnotes,
      this.numberoflessons,
      this.birthday,
      this.registeredby,
      this.signUpdate});

  factory Profile.fromSnapshot(DocumentSnapshot snapshot) {
    return Profile(
      userId: snapshot.id,
      name: snapshot["username"],
      city: snapshot["city"],
      email: snapshot["email"],
      level: snapshot["level"],
      phone: snapshot["phone"],
      image: snapshot["image"],
      quest: snapshot["quest"],
      numberofbooks: snapshot["numberofbooks"],
      numberofnotes: snapshot["numberofnotes"],
      numberoflessons: snapshot["numberoflessons"],
      birthday: snapshot["birthday"],
      registeredby: snapshot["registeredby"],
      signUpdate: snapshot["signUpdate"],
    );
  }
}

profile_service.dart

class ProfileService {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Future <List<Profile>> getProfile() async {
    var ref = _firestore.collection("user");

    var documents = await ref.get();
    
    return documents.docs.map((snapshot) => Profile.fromSnapshot(snapshot)).toList();
  }
}

user_model.dart

class UserModel with ChangeNotifier {
  final ProfileService _profileService = getIt<ProfileService>();
  Future<List<Profile>> getUserName(String query) async {
    var user = await _profileService.getProfile();

    var filteredUserName =
        user.where((profile) => profile.name.startsWith(query ?? "")).toList();

    return filteredUserName;
  }
}

main.dart

actions: [
                  IconButton(
                    icon: Icon(Icons.search),
                    onPressed: () {
                      showSearch(
                        context: context,
                        delegate: UserSearchDelegete(),
                      );
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.more_vert),
                    onPressed: () {},
                  ),
                ],
.
.
.
.
.
.

class UserSearchDelegete extends SearchDelegate {
  @override
  ThemeData appBarTheme(BuildContext context) {
    var selectedThemeColor = Provider.of<ThemeColor>(context).switchTheme;
    final theme = Theme.of(context);
    return theme.copyWith(
      backgroundColor: selectedThemeColor.colorAppBar,
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return SearchedUsers(query: query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Center(
      child: Text(
        "Aradığınız talebenin adını yazınız.",
        style: TextStyle(
          fontWeight: FontWeight.bold,
          color: Colors.black12.withOpacity(0.60),
        ),
      ),
    );
  }
}

class SearchedUsers extends StatelessWidget {
  final String query;

  SearchedUsers({this.query});

  @override
  Widget build(BuildContext context) {
    var model = getIt<UserModel>();
    return FutureBuilder(
        future: model.getUserName(query),
        builder: (BuildContext context, AsyncSnapshot<List<Profile>> snapshot) {
          if (snapshot.hasError)
            return Center(
              child: Text(snapshot.hasError.toString()),
            );
          if (!snapshot.hasData)
            return Center(
              child: CircularProgressIndicator(),
            );
          return ListView(
            children: snapshot.data
                .map((profile) => ListTile(
                      leading: CircleAvatar(
                        backgroundImage: NetworkImage(profile.image == null
                            ? AssetImage("assets/images/profil_resmi.jpg")
                            : profile.image),
                      ),
                      title: Text("${profile.name} - ${profile.city}"),
                      subtitle: Text(
                          "${profile.numberofnotes} not / ${profile.numberofbooks} kitap / ${profile.numberoflessons} ders"),
                    ))
                .toList(),
          );
        });
  }
}

database在此处输入图像描述

Currently you are filtering in your code, but you should let Firestore to filter instead as it's simpler, cheaper and faster.

In your user_model.dart you should only use the returned result from your query which is going to be already filtered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM