Flutter搜索用户名是否存在

问题描述

你好,我在我的应用程序中实现了GestureDetector,每当有人点击该按钮(该按钮是用户名搜索按钮)时,就会激活initateSearch函数。但是,当有人键入一个不存在的用户名时,该用户名应该运行_showSettingPanelFornoplayerFound()方法,那么有人知道为什么没有这种情况。有了这段代码,即使我在文本字段中点击一个现有用户函数_showSettingPanelFornoplayerFound()也会每次显示

 initiateSearch() async {

    if(Firestore.instance.collection("SerX")
        .where("Username")
        .get() != searchEditingController.text){

      _showSettingPanelFornoplayerFound();

    }else if(searchEditingController.text.isEmpty){
      _showSettingPanelForNoEnterSomething();
    }else if(searchEditingController.text.isNotEmpty){
      setState(() {
        isLoading = true;
      });
      await databaseMethods.searchByName(searchEditingController.text)
          .then((snapshot){
        searchResultSnapshot = snapshot;
        print("$searchResultSnapshot");
        setState(() {
          isLoading = false;
          haveUserSearched = true;
        });
      });
    }
  }

解决方法

您应该使用

                var abc = await FirebaseFirestore.instance
                    .collection("Your Collection Name")
                    .where("Username",isEqualTo: "Whatever")
                    .get();
                if (abc.docs.length == 0)//not found
                else 
                //found and you could continue with it

这应该是您的代码

initiateSearch() async {
if(searchEditingController.text.isEmpty){
  _showSettingPanelForNoEnterSomething();
}
else{
  var abc = await FirebaseFirestore.instance.collection("SerX")
    .where("Username",isEqualTo: searchEditingController.text).get();

if(abc.docs.length==0){
    _showSettingPanelForNoPlayerFound();
}
else
{

  setState(() {
    isLoading = true;
  });
  await databaseMethods.searchByName(searchEditingController.text)
      .then((snapshot){
    searchResultSnapshot = snapshot;
    print("$searchResultSnapshot");
    setState(() {
      isLoading = false;
      haveUserSearched = true;
    });
  });
}
}

注释(如果不适用于该错误)。使用最新的FireStore版本