首页 > 解决方案 > 从 TextFormField 获取数据

问题描述

我有 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.dartupdateUserData上的函数。这意味着名称将是用户从键盘输入的数据。我该怎么做?有人能帮助我吗?

标签: flutterdart

解决方案


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

对于简单的 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'),
            ),
          ],
        ),
      ),
    );
  }


推荐阅读