表单字段输入的Flutter Firebase验证 [英] Flutter firebase validation of form field inputs

查看:66
本文介绍了表单字段输入的Flutter Firebase验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flutter和Firebase的新手,我正在尝试验证表单中的用户输入并针对Firebase集合运行它。

I'm new to Flutter and Firebase and I am trying to validate user input from a form and run it up against a the firebase collection.

我问用户创建用户名并要验证Firebase目录中是否存在现有用户名。

I ask users to create a username and want to validate that there is not an existing username in my Firebase directory.

我从检查Flutter Firestore中是否已存在字段。我想为该方法提供一个名称,使用该名称构建一个文档列表,然后确认不存在任何文档。

I got this validation method from the discussion on Check if Field Already exists in Flutter Firestore. I want to feed the method a name, build a List of documents with that name, and confirm that none exist.

  Future<bool> doesNameAlreadyExist(String name) async {
    final QuerySnapshot result = await Firestore.instance
        .collection('user')
        .where('user_id', isEqualTo: name)
        .limit(1)
        .getDocuments();
    final List<DocumentSnapshot> documents = result.documents;
    return documents.length == 1;
  }

我希望能够在文本表单的验证器中调用此方法字段,如下所示。

I hope to be able to call this method within the validator of the text form field as I have done below.

new TextFormField(
          decoration: new InputDecoration(labelText: 'Username'),
          validator: (value) => doesNameAlreadyExist(value) ? "Username already taken" : null,
          onSaved: (value) => _username = value,
        ),

但是,这引发了一个错误,我必须为验证器使用静态类型的布尔值。

However, this throws an error that I must have a static type of bool for the validator.

我的问题:我如何(1)创建能够搜索Firebase的静态布尔方法,或者(2)如何获得与异步功能相同的功能调用(理想情况下,无需构建另一个小部件)?

My question: how can I (1) create a static boolean method that would be able to search Firebase or (2) how can I get the same functionality with the async call (ideally, without having to build another widget)?

推荐答案

将来给出then()方法,您可以使用That。您可以将验证器方法修改为:

Future give then() Method, you can use That. You can modify your validator Method as:

validator: (value) => checkUserValue(value) ? "Username already taken" : null,


  bool _userExist = false;
  checkUserValue<bool>(String user) {
    _doesEmailAlreadyExist(user).then((val){
      if(val){
        print ("UserName Already Exits");
        _userExist = val;
      }
      else{
        print ("UserName is Available");
        _userExist = val;
      }
    });
    return _userExist;
  }

这篇关于表单字段输入的Flutter Firebase验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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