繁体   English   中英

如何使用表单验证来使用Flutter验证集合Firestore中是否存在文档

[英]How to use form validation to verify that document exists inside collection Firestore with Flutter

我想使用表单验证来验证Firestore集合内的文档确实存在抖动。 否则,我会向用户返回带有错误消息的字符串。 用户只能在填写数据库中已经存在的名称后继续操作(否则,他们将无法订阅正确的环境)。 我在代码中使用了带有TextFormField和验证器的Form

下面,我在Form包含了stateful widget

import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

class BuildingScreen extends StatefulWidget {

  @override
  _BuildingScreenState createState() => _BuildingScreenState();
}

class _BuildingScreenState extends State<BuildingScreen> {
  final _formKey = GlobalKey<FormState>();
  bool showSpinner = false;
  String environment;
  bool _autoValidate = false;

  void _validateInputs() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      setState(() {
        showSpinner = true;
      });
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
              child: Column(
                children: <Widget>[
                  Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          textAlign: TextAlign.center,
                          validator: validateEnvironment,
                          onSaved: (String value) {
                            environment = value;
                          },
                        ),
                        RoundedButton(
// the RoundedButton is just a material button with some custom padding
                          buttonTitle: 'Verify',
                          onPressed: () async {
                            _validateInputs();

                            try {
                              if (_formKey.currentState.validate()) {
                                Navigator.pushNamed(
                                    context, RoosterEnvironment.id);
                              }
                              setState(() {
                                showSpinner = false;
                              });
                            } catch (e) {
                              print(e);
                            }
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}

下面是validateEnvironment函数:

import 'package:cloud_firestore/cloud_firestore.dart';

String validateEnvironment(String value) {
  if (value != Firestore.instance.collection('environments').document(value).documentID)
    return 'Environment not on the list';
  else
    return null;
}

在我的Firestore数据库中,我有一个名为“环境”的集合。 在此集合中,我保存了名为“ test”的文档,其字段为“ name:test”。 现在(value != Firestore.instance.collection('environments').document(value).documentID)始终为false,因为firestore实例返回的是TextFormField插入的任何值。 当我将其替换为(value != 'test') ,验证程序运行正常。 我还尝试过命名一个集合“ test”,然后验证它是否像这样存在: (value != Firestore.instance.collection('test'))但这返回了一个'​​collectionReference'实例。

我想知道是否甚至可以进行表单验证检查,还是应该以完全不同的方式进行检查? 任何帮助,将不胜感激!

更新

感谢一些帮助,我更新了我的代码。 现在,我使用TextEditingController和G Griffo代码检查Firestore中是否存在文本字段中的值。 当尚不存在错误消息时,我还没有添加错误消息,但是下面我提供了适用于我的代码。

final _controller = TextEditingController();

static Future<bool> validateEnvironment(String docID) async {
    bool exists = false;
    try {
      await Firestore.instance
          .document("environments/$docID")
          .get()
          .then((doc) {
        if (doc.exists)
          exists = true;
        else
          exists = false;
      });
      print(exists);
      return exists;
    } catch (e) {
      return false;
    }
  }

  void _formvalidate(String docId) async {
    validateEnvironment(docId).then((value) {
      if (value == true) {
        _updateData();
        Navigator.pushNamed(context, RoosterEnvironment.id);
      } else {
      // do something
      }
    });
  }

onPressed我仅包含以下内容:

onPressed: () {
       environment = _controller.text;
       _formvalidate(environment);
},

再次感谢!

我认为Firestore可以查询其中包含所有文档的所有集合数据,但是Firestore无法查询不存在的文档名称。 因此,您可以首先接收集合中的所有文档名称,然后进行验证。 请尝试这个

final snapshots = Firestore.instance.collection('environments').snapshots();

final docNameList = snapshots.map((snapshot) {
  final result = snapshot.documents
      .map((snapshot) =>  snapshot.documentID).toList();
  return result;
});

你可以这样验证

String validateEnvironment(String value) {
   if (!docNameList.data.contains(value))
     return 'Environment not on the list';
  else
     return null;
}

如果有错误,请告诉我。

您可以尝试通过运行查询来搜索文档IDS,以检查您的ID是否已存在于该集合中。我们从执行该操作的静态方法开始

     static Future<bool> validateEnvironment(String docID) async {
    bool exists = false;
    try {
      await Firestore.instance.document("environments/$docID").get().then((doc) {
        if (doc.exists)
          exists = true;
        else
          exists = false;
      });
      return exists;
    } catch (e) {
      return false;
    }
}

最后从您的类中调用该函数

 void  _formvalidate(String docId)async{
    validateEnvironment(docId).then((value) {
      if (!value) {
       //file not found do dome stuff
....
      } else {
       //document exists do some stuff
      }
});
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM