如何用flutter编辑firebase现有文档



我尝试在flutter中构建一个笔记应用程序,当我尝试编辑旧笔记时,我没有看到任何更改,它会使用旧值。

那是我的收藏

我的主页:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:story_note/pages/ajoutNote.dart';
import 'package:story_note/pages/authController.dart';
import 'package:story_note/pages/detailNote.dart';
import 'package:story_note/pages/modifierNote.dart';
import 'package:story_note/pages/modifyNote.dart';
import 'package:timeago/timeago.dart' as timeago;
class Home extends StatefulWidget{
@override
_HomeState createState()=>_HomeState();
}
class _HomeState extends State<Home>{
FirebaseUser currentUser;
String nomUser,emailUser;
Widget _boiteDuDialog(BuildContext, String nom, String email){
return SimpleDialog(
contentPadding: EdgeInsets.zero,
children:<Widget> [
Padding(padding: EdgeInsets.all(8.0),
child: Column(
children:<Widget> [
Text('$nom',style: Theme.of(context).textTheme.title,),
Text('$email',style: Theme.of(context).textTheme.subtitle1,),
SizedBox(height: 10.0,),
Wrap(
children:<Widget> [
FlatButton(color: Colors.red,onPressed:()async{
FirebaseAuth _auth = FirebaseAuth.instance;
await _auth.signOut();
setState(() {
Navigator.pop(context);
});
}, child:Text('Déconnexion')),
FlatButton(onPressed:(){
Navigator.pop(context);
}, child: Text('Annuler'))
],
)
],
),
),
],
);
}
@override
Widget build(BuildContext context) {
// TODO: implement build
final utilisateur = Provider.of<Utilisateur>(context);
FirebaseAuth.instance.currentUser().then((FirebaseUser user){
setState(() {
this.currentUser=user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'pas id';
}
}
GetCurrentUserData(idUser: utilisateur.idUser).dataUser.forEach((snapshot){
this.nomUser = snapshot.nomComplet;
this.emailUser = snapshot.email;
});
Widget _buildListItem(DocumentSnapshot document){
Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').snapshots();
Timestamp t = document['timestamp'];
final DateTime d = t.toDate();
final DateTime h = DateTime.now();
final diff = d.difference(h).inMinutes;
final date = new DateTime.now().subtract(new Duration(minutes: diff));
String realdate = timeago.format(date);
return Dismissible (
key: new Key(ObjectKey(document.data.keys).toString()),
onDismissed: (direction)async{
await Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').document().delete();
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('${document['titre']} was deleted',style: new TextStyle(color: Colors.red),),
)
);
},
background: new Container(
color: Colors.red,
),
child:Container(
padding: EdgeInsets.symmetric(horizontal: 10),
height: 80,
alignment: Alignment.center,
child:Card(
elevation: 10.0,
color: Theme.of(context).primaryColor,
shadowColor: Colors.white24,
child:new ListTile(
onTap:(){
print('cest fait');
Navigator.push(context, MaterialPageRoute(builder: (context)=>ModifierNote(
titre:document['titre'],
note:document['note']
)));
},
leading: Icon(Icons.mood_rounded,color: Colors.blue,size: 30,),
title: new Text('${document['titre']}',style: new TextStyle(fontSize: 20,fontWeight: FontWeight.bold),textAlign: TextAlign.justify,),
subtitle: new Text('${document['note']}',maxLines: 1,),
trailing: new Text(realdate),
),
)
)
);
}
return Scaffold(
appBar: AppBar(
title: Text('Story Notes',),
centerTitle: true,
backgroundColor: Theme.of(context).primaryColor,
actions: [
IconButton(icon: Icon(Icons.search_rounded), onPressed:(){
}),
IconButton(icon: Icon(Icons.person), onPressed:()=>showDialog(context: context,builder: (context)=>
_boiteDuDialog(context,nomUser,emailUser))),
],
),
body: Padding(
padding: EdgeInsets.only(top: 25),
child:StreamBuilder(
stream: Firestore.instance.collection('utilisateurs').document(utilisateur.idUser).collection('notes').snapshots(),
builder: (context,snapshot){
if(!snapshot.hasData)
return Text('loading....');
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder:(context,index)=>
_buildListItem(snapshot.data.documents[index]),

);
},
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.blue,
child: Icon(Icons.note_add,),
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>AjoutNote()));
},
),
);
}
}

我的修改页面:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class ModifierNote extends StatefulWidget{
final String titre,note;
ModifierNote({this.titre,this.note});
@override
ModifierNoteState createState()=> ModifierNoteState();
}
class ModifierNoteState extends State<ModifierNote>{
final CollectionReference collectionUser = Firestore.instance.collection('utilisateurs');
FirebaseUser currentUser;
final _formkey = GlobalKey<FormState>();
bool _titreValid = true;
bool _noteValid = true;
@override
Widget build(BuildContext context) {
// TODO: implement build
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() {
this.currentUser = user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'Pas id';
}
}
String titre1 = widget.titre;
String note1 = widget.note;
final DateTime timestamp = DateTime.now();
modifierNotes()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.setData({
'titre': titre1,
'note': note1,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: Text('Notes'),
actions: [
RaisedButton(
onPressed:()async{
if(_formkey.currentState.validate()){
modifierNotes();
}
},
child:Text('Modifier')
),
],
),
body: Stack(
children: [
SingleChildScrollView(
child:Card(
elevation: 15,
color: Theme.of(context).primaryColor,
child: Form(
key: _formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children:<Widget> [
TextFormField(
initialValue: titre1,
decoration: InputDecoration(
labelText: 'Titre',
prefixIcon: Icon(Icons.speaker_notes_sharp),
),
validator: (val) =>
val.isEmpty ? 'Entrez un titre' : null,
onChanged: (val)=>setState(()=>titre1 = val),
),
TextFormField(
initialValue: note1,
keyboardType: TextInputType.multiline,
maxLines: 5000,
autofocus: true,
decoration: InputDecoration(
hintText: 'Comment vous sentez vous ?',
hintStyle: new TextStyle(fontSize: 20),
),
validator: (val) =>
val.isEmpty ? 'Entrez une note' : null,
onChanged: (val)=>setState(()=>note1 = val),
),
],
),
),
),
),
],
),
);

}
}

和Addpage:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class AjoutNote extends StatefulWidget{
AjoutNoteState createState()=> AjoutNoteState();
}
class AjoutNoteState extends State<AjoutNote>{
String titre;
String note;
final _formkey = GlobalKey<FormState>();
final CollectionReference collectionUser = Firestore.instance.collection('utilisateurs');
final DateTime timestamp = DateTime.now();
FirebaseUser currentUser;
@override
Widget build(BuildContext context) {
// TODO: implement build
FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
setState(() {
this.currentUser = user;
});
});
String _idUser(){
if(currentUser!=null){
return currentUser.uid;
}else{
return 'Pas id';
}
}
enegistrezNote()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.setData({
'titre': titre,
'note': note,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}
return Scaffold(
backgroundColor: Theme.of(context).primaryColor,
appBar: AppBar(
title: Text('Ajouter une note'),
centerTitle: true,
backgroundColor: Theme.of(context).primaryColor,
actions: [
RaisedButton(onPressed:(){
if(_formkey.currentState.validate()){
enegistrezNote();
}
},
child: Text("Enregistrez"),
),
],
),
body: new Container(
child:SingleChildScrollView(
child: Card(
elevation: 15,
color: Theme.of(context).primaryColor,
child: Form(
key: _formkey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children:<Widget> [
TextFormField(
decoration: InputDecoration(
labelText: 'Titre',
prefixIcon: Icon(Icons.speaker_notes_sharp)
),
onChanged: (val)=>titre=val,
),
TextFormField(
keyboardType: TextInputType.multiline,
maxLines: 5000,
autofocus: true,
decoration: InputDecoration(
hintText: 'Comment vous sentez vous ?',
hintStyle: new TextStyle(fontSize: 20),
),
onChanged: (val)=>note=val,
)
],
),
),
),
),
),
resizeToAvoidBottomPadding: true,
);
}
}

当我尝试修改时,我看不到任何变化。

使用更新方法代替设置,我为您做了更改:

modifierNotes()async{
await collectionUser.document(_idUser()).collection('notes')
.document('note')
.update({
'titre': titre1,
'note': note1,
'timestamp':timestamp
});
this.setState(() {
Navigator.pop(context);
});
}

最新更新