如何使willPopScope不返回应用程序,颤抖

时间:2020-11-12 19:58:16

标签: flutter searchbar

我使用此文本字段进行搜索,除用户单击后退按钮并由于onWillPopScope退出应用程序外,其他所有内容都正常运行。我如何解决此问题以返回菜单?

这是我的文本字段

Textfield

这就是我搜索时发生的情况 Exiting app


TextEditingController searchController = new TextEditingController();

StreamSubscription _recipeAddedSub;

列出allRecipes = [];

列出searchRecipes = [];

bool _isSearching;

食谱;

var recipeRef = FirebaseDatabase.instance.reference();
    void initState(){
     super.initState();
      _recipeAddedSub = recipeRef.child('recipes').onChildAdded.listen(recipesEvent);
 }

    DatabaseReference getRecipeRef(){
      recipeRef = recipeRef.root();
      return recipeRef;
    }
    
    void recipesEvent(Event event){
      //listen from firebase
      Recipes recipes = new Recipes.fromSnapShot(event.snapshot);
      setState(() {
        allRecipes.add(recipes);
      });
    }
   Future<bool> _onBackPressed() async {
   if(_isSearching ==true){
    setState(() {
      searchRecipe("");
     _isSearching = false;
     allRecipes.add(recipes);
    }); 

     return false;
   }
   else {
     return true;
   }
 }
  

我的搜索方法:

    void searchRecipe(String searchVal){
           _isSearching = true;
            searchRecipes.clear();
          setState(() {
            allRecipes = searchRecipes;
          });
          String name, about, image, ingred, instruc;
        Query query = recipeRef.child("recipes").orderByChild("name").equalTo(searchVal.trim());
        query.once().then((snapshot) {
            snapshot.value.forEach((key, value){
              name = value["name"].toString().trim();
              image = value["image"].toString().trim();
              about = value["about"].toString().trim();
              instruc = value["instruction"].toString().trim();
              ingred = value["ingred"].toString().trim();
              searchRecipes.add(new Recipes(key, name, ingred, instruc, about,image));
            });
        });

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

Scaffold小部件中包装WillPopScope。将_onBackPressed()传递到小部件的onWillPop参数。

已更新

Future<bool> _onBackPressed() async {
    if(_isSearching == true){
      setState(() {
        _isSearching = false;
        // maybe clear search text, update recipe list, etc.
      });
      return false;
   }else {
     return true; 
   } 
}