【问题标题】:Getting data from TextFormField从 TextFormField 获取数据
【发布时间】:2021-09-08 15:32:43
【问题描述】:

我有 3 个文件:
database.dart

    import 'package:cloud_firestore/cloud_firestore.dart';
    
    class DatabaseService{
      final String uid;
      DatabaseService({required this.uid});
      final CollectionReference userCollection = FirebaseFirestore.instance.collection('users');
    
      Future updateUserData(String name) async {
        return await userCollection.doc(uid).set({
          'name': name,
        });
      }

另一个名为 auth.dart

的文件

class AuthService{
  final FirebaseAuth _auth = FirebaseAuth.instance;
    Future registerWithEmailAndPassword(String email, String password) async {
        try{
          UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
          User? user = result.user;
    
          // Create a new document for the user with the uid
          await DatabaseService(uid: user!.uid).updateUserData();
          return _userFromFirebaseUser(user);
        }
        catch(e){
          print(e);
          return null;
        }
      }
}  

还有一个名为 register.dart 的文件,代码如下:

import 'package:flutter/material.dart';
class Register extends StatefulWidget {
  const Register({Key? key}) : super(key: key);

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

class _RegisterState extends State<Register> {
  String name = '';
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Form(
          child: Column(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration
                  (
                    contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                    hintText: "Full Name",
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))
                ),
                validator: (val) => val!.isEmpty ? 'Enter an email' : null,
                onChanged: (val){
                  setState(() => name = val);
                },
              ),
            ],
          ),
        ),
    );

  }
}

我想从 register.dart 上的 TextFormField 获取数据以传递到 auth.dart 上的函数 updateUserData。这意味着名称将是用户从键盘输入的数据。 我该怎么做?有人可以帮帮我吗?

【问题讨论】:

  • 我可以看到您已经获取了 name 变量中的值。尝试在 onchanged 上打印。
  • 我需要在 updateUserData() 中的文件 auth.dart 上调用该名称变量。我该怎么做?
  • 使用函数回调
  • @p2kr 它也不起作用
  • @p2kr 你的意思是 TextEditingController 吗?

标签: flutter dart


【解决方案1】:

在您的情况下,您将 Form 与 TextFormField 结合使用,为了检索您的值,您可以为您的 Form 设置一个 Key 并使用它来检索您的数据。

对于简单的 TextField,您可以为其分配一个 TextEditingController 并以这种方式检索其值。

这是一个包含表单、密钥和验证器的示例:

然后您可以使用此值以名称作为参数调用您的身份验证函数。

  final _formKey = GlobalKey<FormState>();
  String name = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            TextFormField(
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (newValue) {
                setState(() => name = newValue);
              },
            ),
            ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState!.save(); // Calls onSaved method in your fields
                  // Other actions such as call your update method
                }
              },
              child: Text('Save'),
            ),
          ],
        ),
      ),
    );
  }

【讨论】:

  • 但问题是如何从 auth.dart 文件的 AuthService 类中调用 TextFormField 中的值?
  • 您必须通过提供者公开您的 DatabaseService,例如使其在您的应用程序中可用并调用 DatabaseService dbs = DatabaseService(); dbs.updateUsername(value)
  • 如果您是初学者,我会推荐 Getx 软件包,它非常易于理解和使用。
猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 2020-08-15
  • 2018-12-25
  • 2023-02-07
  • 1970-01-01
  • 2022-10-06
相关资源
最近更新 更多