在 flutter 中发布到 firestore 时如何验证文本字段?

发布于 2025-01-12 08:50:11 字数 1468 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只有影子陪我不离不弃 2025-01-19 08:50:11

看来问题是以下代码中的控制流的一个简单错误(请参阅 // 注释):

 void _submitData() async {
    final _isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();
    if (_isValid) {
      _formKey.currentState!.save();
    } // <----- this should not be here!
    try {
      setState(() {
        _isLoading = true;
      });
      final User? user = _auth.currentUser;
      final _uid = user!.uid;
      final orderId = ModalRoute.of(context)!.settings.arguments as String;
      FirebaseFirestore.instance
          .collection('orders')
          .doc(orderId)
          .set({
        'userId': _uid,
        'name': _name,
        'phoneNumber': _phoneNumber,
        'addressType': _addressType,
        'address': _fullAddress,
        'area': _area,
        'city': _city,
        'deliverySlot': _deliverySlotValue,
      }, SetOptions(merge: true));

    } catch (error) {
      _globalMethods.authDialog(context, error.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
      Navigator.of(context).pushReplacementNamed(OrderSuccess.routeName);
    }
  }

如您所见,即使用户输入无效,您仍然会继续将结果上传到 Firebase。

尝试像这样纠正:

void _submitData() async {
    final _isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();
    if (_isValid) {
      _formKey.currentState!.save();
      try {
        setState(() {
          _isLoading = true;
        });
        final User? user = _auth.currentUser;
        final _uid = user!.uid;
        final orderId = ModalRoute.of(context)!.settings.arguments as String;
        FirebaseFirestore.instance.collection('orders').doc(orderId).set({
          'userId': _uid,
          'name': _name,
          'phoneNumber': _phoneNumber,
          'addressType': _addressType,
          'address': _fullAddress,
          'area': _area,
          'city': _city,
          'deliverySlot': _deliverySlotValue,
        }, SetOptions(merge: true));
      } catch (error) {
        _globalMethods.authDialog(context, error.toString());
      } finally {
        setState(() {
          _isLoading = false;
        });
        Navigator.of(context).pushReplacementNamed(OrderSuccess.routeName);
      }
    } else {
      // do nothing
    }
  }

It appears that the problem is a simple mistake with your control flow in the following code (see // comment):

 void _submitData() async {
    final _isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();
    if (_isValid) {
      _formKey.currentState!.save();
    } // <----- this should not be here!
    try {
      setState(() {
        _isLoading = true;
      });
      final User? user = _auth.currentUser;
      final _uid = user!.uid;
      final orderId = ModalRoute.of(context)!.settings.arguments as String;
      FirebaseFirestore.instance
          .collection('orders')
          .doc(orderId)
          .set({
        'userId': _uid,
        'name': _name,
        'phoneNumber': _phoneNumber,
        'addressType': _addressType,
        'address': _fullAddress,
        'area': _area,
        'city': _city,
        'deliverySlot': _deliverySlotValue,
      }, SetOptions(merge: true));

    } catch (error) {
      _globalMethods.authDialog(context, error.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
      Navigator.of(context).pushReplacementNamed(OrderSuccess.routeName);
    }
  }

As you can see, even if the user input is not valid, you still continue to upload the results to Firebase anyway.

Try correcting like this:

void _submitData() async {
    final _isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();
    if (_isValid) {
      _formKey.currentState!.save();
      try {
        setState(() {
          _isLoading = true;
        });
        final User? user = _auth.currentUser;
        final _uid = user!.uid;
        final orderId = ModalRoute.of(context)!.settings.arguments as String;
        FirebaseFirestore.instance.collection('orders').doc(orderId).set({
          'userId': _uid,
          'name': _name,
          'phoneNumber': _phoneNumber,
          'addressType': _addressType,
          'address': _fullAddress,
          'area': _area,
          'city': _city,
          'deliverySlot': _deliverySlotValue,
        }, SetOptions(merge: true));
      } catch (error) {
        _globalMethods.authDialog(context, error.toString());
      } finally {
        setState(() {
          _isLoading = false;
        });
        Navigator.of(context).pushReplacementNamed(OrderSuccess.routeName);
      }
    } else {
      // do nothing
    }
  }
七七 2025-01-19 08:50:11

唯一可能的原因是 _addressType 的初始值为 null
因为它是一个 String? 变量,所以如果用户没有选择“Delivery Slot”
保存后的结果将是 null

您需要做的是检查 _addressType 的值是否为 null 然后继续保存表单,因为您的表单不会检查它是否为空。

The only possible reason is because of _addressType it's initial value is null
since it's a String? variable so if the user didn't select a "Delivery Slot"
the result of it after saving would be null,

what you need to do, it to check the value of _addressType if it's null or not then proceed to saving the form because your form doesn't check it if it's null or not.

与往事干杯 2025-01-19 08:50:11

您可以将表单验证器添加到提交按钮本身。当您单击“提交”按钮时,以下代码将起作用。

Padding(
   padding: const EdgeInsets.all(48.0),
   child: SizedBox(
   child: ElevatedButton(
     onPressed: (){
       if (_formKey.currentState!.validate()){
         _submitData;
     }
   },
   child: _isLoading
   ? const CircularProgressIndicator()
   : const Text(
   'S U B M I T',
    style: TextStyle(color: Colors.white),
   ),
  ),
 ),
),

You can add the form validator to the submit button itself. The below code works when you click on the submit button.

Padding(
   padding: const EdgeInsets.all(48.0),
   child: SizedBox(
   child: ElevatedButton(
     onPressed: (){
       if (_formKey.currentState!.validate()){
         _submitData;
     }
   },
   child: _isLoading
   ? const CircularProgressIndicator()
   : const Text(
   'S U B M I T',
    style: TextStyle(color: Colors.white),
   ),
  ),
 ),
),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文