【问题标题】:Flutter - Async Validator of TextFormFieldFlutter - TextFormField 的异步验证器
【发布时间】:2019-04-11 04:33:04
【问题描述】:

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

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

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;
  }

【问题讨论】:

  • This 是解决方法,它为我完成了这项工作。
  • 对我来说非常好用,非常感谢!
  • 如果您想出了自己的答案,请为您的问题添加答案并将其标记为正确。这将对其他用户有所帮助。

标签: android ios dart flutter


【解决方案1】:

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

类似:

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,
)

【讨论】:

  • 如果用户快速键入并且 checkRecipe 函数有延迟,这会起作用吗?另外,await 会阻止 UI 吗?
【解决方案2】:

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

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

您可以为validator 传入Future&lt;bool&gt; 函数,并设置文本发送到服务器之前的时间间隔。

代码可在github获取。

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2019-12-04
    • 1970-01-01
    • 2023-01-12
    • 2020-10-27
    • 2020-10-01
    • 2019-08-12
    • 2021-08-10
    • 2019-08-17
    相关资源
    最近更新 更多