【发布时间】: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 吗?