繁体   English   中英

如何从另一个 dart 文件访问值?

[英]How to access values from another dart file?

我是 flutter 的新手。这里我将一个值存储到变量doc_id中,我想在另一个名为 comments.dart 的文件中使用该值。 所以我做了类似下面的事情,但它在 comment.dart 中给出了 null 值。

await FirebaseFirestore.instance
    .collection('blogs')
    .add({
    'title': titleController.text,                         
}).then((value) {
  doc_id = value.id;

  comment(postid: docid);

  successAlert(context);
}).catchError((error) => 
 errorAlert(context));

评论.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);
  } 
}

只需创建一个全局变量并从那里分配

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

最后赋值

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

最后在你的 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);
  } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM