Flutter-TextFormField的异步验证器

时间:2018-11-07 17:24:24

标签: android ios dart flutter

在我的应用程序中,用户必须在textformfield中插入一个名称。当用户编写查询时,应该对数据库进行查询,该查询控制名称是否已经存在。该查询返回名称存在的次数。到现在,只要按一下按钮,我就可以做到。

这是返回名称计数的函数:

checkRecipe(String name) async{
    await db.create();
    int count = await db.checkRecipe(name);
    print("Count: "+count.toString());
    if(count > 0) return "Exists";
  }

这是TextFormField,应该通过异步验证:

TextField(
    controller: recipeDescription,
    decoration: InputDecoration(
       hintText: "Beschreibe dein Rezept..."
    ),
    keyboardType: TextInputType.multiline,
    maxLines: null,
    maxLength: 75,
    validator: (text) async{ //Returns an error
       int count = await checkRecipe(text);
       if (count > 0) return "Exists";
    },
 )

代码错误是:

  

不能将参数类型Future分配给参数类型   字符串

我确实知道错误的含义。但是我不知道该如何解决。如果有人可以帮助我,那将太好了。

我找到了一个solution

我的代码现在看起来像这样:

//My TextFormField validator
validator: (value) => checkRecipe(value) ? "Name already taken" : null,

//the function
  checkRecipe<bool>(String name) {
    bool _recExist = false;
    db.create().then((nothing){
      db.checkRecipe(name).then((val){
        if(val > 0) {
          setState(() {
            _recExist = true;
          });
        } else {          
          setState(() {
            _recExist = false;
          });
        }
      });
    });
    return _recExist;
  }

2 个答案:

答案 0 :(得分:2)

也许您可以使用async处理程序运行onChange检查并设置一个本地变量来存储结果。

类似:

TextFormField(
  controller: recipeDescription,
  decoration: InputDecoration(hintText: "Beschreibe dein Rezept..."),
  keyboardType: TextInputType.multiline,
  maxLines: null,
  maxLength: 75,
  onChanged: (text) async {
    final check = await checkRecipe(text);
    setState(() => hasRecipe = check);
  },
  validator: (_) => (hasRecipe) ? "Exists" : null,
)

答案 1 :(得分:0)

我希望我们的一个应用程序具有相同的行为,并最终编写了一个小部件(我最近将其发布到 pub.dev)。

enter image description here

AsyncTextFormField(
    controller: controller,
    validationDebounce: Duration(milliseconds: 500),
    validator: isValidPasscode,
    hintText: 'Enter the Passcode')

您可以为 Future<bool> 传入一个 validator 函数,并在将文本发送到服务器之前设置一个间隔。

代码可在 github 获得。

相关问题