SearchDelegate 在单击搜索按钮时向屏幕返回“true”

Posted

技术标签:

【中文标题】SearchDelegate 在单击搜索按钮时向屏幕返回“true”【英文标题】:SearchDelegate returns "true" to screen when click to search button 【发布时间】:2021-06-15 21:31:30 【问题描述】:

当我在我的应用程序中搜索用户时,我会提取并过滤 Firestore 中的用户。之后,我将其显示为屏幕上的列表。但是当您按下搜索按钮时,屏幕中间会显示“true”,名称不会显示。怎么了?

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;
  

ma​​in.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(),
          );
        );
  

数据库

【问题讨论】:

你的数据库的结构也可以加一下吗? @FaridShumbar 我添加了一张显示相关位置的图片 【参考方案1】:

目前您正在代码中进行过滤,但您应该使用Firestore to filter instead,因为它更简单、更便宜且更快。

在您的user_model.dart 中,您应该只使用查询返回的结果,该结果将被过滤。

【讨论】:

你好@pirekare。任何进展?这是answer your question吗?

以上是关于SearchDelegate 在单击搜索按钮时向屏幕返回“true”的主要内容,如果未能解决你的问题,请参考以下文章

Flutter - 更改 SearchDelegate 的搜索提示文本

搜索委托,当我点击搜索按钮时,它会显示带有错误子项的红屏! =空

在 SearchDelegate Flutter 中更改 searchFieldLabel 的字体样式

单击laravel vuejs中的按钮后如何隐藏bootstrap-vue模式

如何在 SearchDelegate 的 buildResults 中传递更新 UI 值?

如何在点击FB like按钮时向Facebook用户发送电子邮件?