Flutter-TextFormField的异步验证器 [英] Flutter - Async Validator of TextFormField

查看:496
本文介绍了Flutter-TextFormField的异步验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app the user has to insert a name in the textformfield. While the user is writing a query should be made to the database, that controls if the name already exists. This query returns the number of how many times the name exists. Till now I am able to make it when I press a button.

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

This is the function that returns the count of the names:

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

这是TextFormField,应该异步验证:

And this is the TextFormField, which should be validated async:

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无法分配给参数类型
字符串

The argument type Future can't be assigned to the parameter type String

我确实知道错误的含义。但是我不知道该如何解决。

I do know what the error means. But I do not know how to work around could look like. It would be awesome if somebody could help me.

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

My Code looks now like this:

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


推荐答案

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

Perhaps you could run your async check using the onChange handler and set a local variable to store the result.

类似的东西:

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

这篇关于Flutter-TextFormField的异步验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆