flutter - 从 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
上的函数。这意味着名称将是用户从键盘输入的数据。我该怎么做?有人能帮助我吗?
解决方案
在您的情况下,您将表单与 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'),
),
],
),
),
);
}
推荐阅读
- neo4j - 如果不存在则在neo4j中创建关系,如果存在则更新属性值
- reactjs - React-Router-V4 历史推送后从 React 组件获取数据
- maven - 使用 docker 容器的 Spring Boot 集成测试多模块 maven 应用程序
- c# - 构建字符串时如何保持上一行的缩进
- python - Django Web 服务器启动但不请求任何内容
- python - GT521F52 指纹传感器库
- angular - 如何设置嵌套 ngFor
- php - 上传图片到 laravel 的问题
- php - Paytm PHP 函数 mcrypt_get_block_size() 已弃用问题
- c# - 使用 C# 中的 API 设置 Google 日历事件的颜色