Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

android - Flutter - Async Validator of 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";
  }

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";
    },
 )

The error of the code is:

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.

I have found a solution.

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;
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Something like:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...