Home > OS >  How to access values from another dart file?
How to access values from another dart file?

Time:01-07

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);
  } 
}

CodePudding user response:

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));

CodePudding user response:

If your comment widget is a new screen,You should use Navigator to navigate to particular screen with passing the doc_id in constructor.

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => comment(postid: docid)),
  );
  • Related