forms - 使用 Flutter 将表单上传到 Firestore
问题描述
我对如何在我的颤振应用程序中将表单上传到 Firestore 感到困惑。我已经阅读了许多教程,并且能够登录 Firebase 并将 Firestore 中的数据检索到我的颤振应用程序中,但我不知道如何将包含大量文本字段的表单上传到 Firestore。
示例:文档标题“书籍”文本字段将包括:标题、作者等。
*** // 下面是我的页面,它确实从 Firestore 导入数据(这有效)。我添加了一个按钮,该按钮转到另一个页面,我试图在其中添加要上传到 Firestore 的表单(这不起作用)。页面加载有效,但未设置上传到 Firestore。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
class FireStore extends StatelessWidget {
FireStore({this.auth, this.onSignedOut});
final BaseAuth auth;
final VoidCallback onSignedOut;
void _signOut () async {
try {
await auth.signOut();
onSignedOut();
} catch (e) {
print (e);
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text ('Welcome'),
actions: <Widget>[
new FlatButton(
child: new Text('Logout', style: new TextStyle(fontSize: 17.0, color: Colors.white)),
onPressed: _signOut
)
]
),
body: new StreamBuilder(
stream: Firestore.instance.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return new GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']),
);
}).toList(),
);
},
),
floatingActionButton: new FloatingActionButton(
elevation: 0.0,
child: new Icon(Icons.add),
backgroundColor: new Color(0xFFE57373),
onPressed: (){
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new UploadFormField()),
);
}
)
);
}
}
// UPLOAD TO FIRESTORE
class UploadFormField extends StatefulWidget {
@override
_UploadFormFieldState createState() => _UploadFormFieldState();
}
class _UploadFormFieldState extends State<UploadFormField> {
GlobalKey<FormState> _key = GlobalKey();
bool _validate = false;
String title, author;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Upload'),
),
body: new SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.all(15.0),
child: new Form(
key: _key,
autovalidate: _validate,
child: FormUI(
)),
),
),
),
);
}
Widget FormUI() {
return new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(hintText: 'Title'),
validator: validateTitle,
onSaved: (String val) {
title = val;
}
),
new TextFormField(
decoration: new InputDecoration(hintText: 'Author'),
validator: validateAuthor,
onSaved: (String val) {
author = val;
}
),
new SizedBox(height: 15.0),
new RaisedButton(onPressed: _sendToServer, child: new Text('Upload'),
)
],
);
}
String validateTitle (String value) {
String pattern = r' (^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0){
return 'Title is required';
} else if (!regExp.hasMatch(value)) {
return "Title must be a-z and A-Z";
}
return null;
}
String validateAuthor (String value) {
String pattern = r' (^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(pattern);
if (value.length == 0){
return 'Author is required';
} else if (!regExp.hasMatch(value)) {
return "Author must be a-z and A-Z";
}
return null;
}
_sendToServer(){
if (_key.currentState.validate() ){
//No error in validator
_key.currentState.save();
print ("Title $title");
print ("Author $author");
} else {
// validation error
setState(() {
_validate = true;
});
}
}
}
解决方案
我能够通过以下方式解决问题:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
class FireStore extends StatelessWidget {
FireStore({this.auth, this.onSignedOut});
final BaseAuth auth;
final VoidCallback onSignedOut;
void _signOut () async {
try {
await auth.signOut();
onSignedOut();
} catch (e) {
print (e);
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text ('Welcome'),
actions: <Widget>[
new FlatButton(
child: new Text('Logout', style: new TextStyle(fontSize: 17.0, color: Colors.white)),
onPressed: _signOut
)
]
),
body: new StreamBuilder(
stream: Firestore.instance.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return new GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']),
);
}).toList(),
);
},
),
floatingActionButton: new FloatingActionButton(
elevation: 0.0,
child: new Icon(Icons.add),
backgroundColor: new Color(0xFFE57373),
onPressed: (){
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new UploadFormField()),
);
}
)
);
}
}
// UPLOAD TO FIRESTORE
class UploadFormField extends StatefulWidget {
@override
_UploadFormFieldState createState() => _UploadFormFieldState();
}
class _UploadFormFieldState extends State<UploadFormField> {
GlobalKey<FormState> _key = GlobalKey();
bool _validate = false;
String title, author;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Upload'),
),
body: new SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.all(15.0),
child: new Form(
key: _key,
autovalidate: _validate,
child: FormUI(),
),
),
),
),
);
}
Widget FormUI() {
return new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(hintText: 'Title'),
validator: validateTitle,
onSaved: (String val) {
title = val;
}
),
new TextFormField(
decoration: new InputDecoration(hintText: 'Author'),
validator: validateAuthor,
onSaved: (String val) {
author = val;
}
),
new SizedBox(height: 15.0),
new RaisedButton(onPressed: _sendToServer, child: new Text('Upload'),
)
],
);
}
String validateTitle(String value) {
String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Title is Required";
} else if (!regExp.hasMatch(value)) {
return "Title must be a-z and A-Z";
}
return null;
}
String validateAuthor(String value) {
String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Author is Required";
} else if (!regExp.hasMatch(value)) {
return "Author must be a-z and A-Z";
}
return null;
}
_sendToServer(){
if (_key.currentState.validate() ){
//No error in validator
_key.currentState.save();
Firestore.instance.runTransaction((Transaction transaction) async {
CollectionReference reference = Firestore.instance.collection('books');
await reference.add({"Title": "$title", "Author": "$author"});
});
} else {
// validation error
setState(() {
_validate = true;
});
}
}
}
推荐阅读
- php - ACF WP_Query 按分类字段筛选
- javascript - 我想用 (new Promise) 将数据存储在变量中?javascript
- html - 跨单元格组在 HTML 表格中居中文本
- javascript - 在没有 onChange 的情况下反应文本表单字段
- php - 如何通过 PHP 登录到另一个站点并下载站点中的特定页面
- node.js - gmail api 无法正常发送带附件的电子邮件
- javascript - 所有重要的网站 Prestashop 内容都必须在关闭 js 并以纯 html 形式提供的情况下可供搜索机器人使用
- javascript - 从 php/json 转换时,JavaScript 中只出现一个结果
- go - fmt.Println 不打印整个浮点数
- python - 使用 VsCode 调试 python 模块