Flutter - TextFormField 的异步验证器

13 android ios dart flutter

在我的应用程序中,用户必须在文本表单字段中插入名称。当用户编写查询时,应该对数据库进行查询,这控制该名称是否已存在。该查询返回该名称存在的次数。到目前为止,我只要按下按钮就可以做到。

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

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

这是 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";
    },
 )
Run Code Online (Sandbox Code Playgroud)

代码的错误是:

参数类型 Future 不能分配给参数类型 String

我确实知道该错误意味着什么。但我不知道如何解决可能看起来像。如果有人能帮助我,那就太好了。

我已经找到了解决办法

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

//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;
  }
Run Code Online (Sandbox Code Playgroud)

You*_*Ken 9

也许您可以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,
)
Run Code Online (Sandbox Code Playgroud)


sni*_*kid 5

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

在此输入图像描述

AsyncTextFormField(
    controller: controller,
    validationDebounce: Duration(milliseconds: 500),
    validator: isValidPasscode,
    hintText: 'Enter the Passcode')
Run Code Online (Sandbox Code Playgroud)

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

该代码可在github上找到。