Reputation: 171
I am new to flutter .Here I stored a value to a variable doc_id
,I want to use this value in another file called comments.dart . So I did something like below but it gives null value in comment.dart .
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Comment.dart
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
@override
Widget build(BuildContext context) {
return
Text(widget.postid);
}
}
Upvotes: 0
Views: 64
Reputation: 5984
You can use: https://pub.dev/packages/shared_preferences
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
await prefs.setString('doc_id', postid); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Finally use it in your class
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
@override
void initState() {
super.initState();
widget.postid = prefs.getString('doc_id'); // get the value
setState(() {});
}
@override
Widget build(BuildContext context) {
return
Text(postid);
}
}
Upvotes: 0
Reputation: 5984
Just create a global variable and assign from there
String postid = "";
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
@override
Widget build(BuildContext context) {
return
Text(postid);
}
}
void setPostID(String s) { // get value
postid = s;
}
Finally assign the value
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
setPostID(value.id); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Upvotes: 1