正在从TextFormField获取数据



我有三个文件:
数据库.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将是用户从键盘输入的数据。我该怎么做?有人能帮我吗?

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

在一个简单的TextField的情况下,您将为它分配一个TextEditingController,并以这种方式检索它的值。

下面是一个包含Form、Key和验证器的示例:

然后,您可以使用该值以名称作为参数来调用您的auth-foction。

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'),
),
],
),
),
);
}

最新更新