【问题标题】:Flutter: pass data to stateFlutter:将数据传递给状态
【发布时间】:2019-08-19 22:53:49
【问题描述】:

我正在尝试将数据传递到启动 API 调用的块中,但出现错误:

“在初始化器中只能访问静态成员”

这可能吗?我的方法完全错误吗?

我也尝试将postid 切换为静态,但不确定如何实际访问该状态下的postid

代码:

class ViewPost extends StatefulWidget {
   int postid; // sent from previous screen

}

ViewPost(
  {Key key,
  this.postid     
  })
  : super(key: key);
}

我需要访问 postid 的状态:

@override
  _ViewPostState createState() => _ViewPostState();
}

class _ViewPostState extends State<ViewPost> {


final int postid; // somehow I'd need to access postid here

  final PostBlog _PostBloc =
  PostBloc(httpClient: http.Client(), postid: postid);
}



  _ViewBlogState() { 
_postBloc.dispatch(Fetch());
}

构建:

@override
  Widget build(BuildContext context) {

return Scaffold(
  appBar: AppBar(
    title: Text(widget.name),
    backgroundColor: Colors.black,
    automaticallyImplyLeading: true,

    leading: IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () onPressed: ()  => Navigator.pop(context, true),

    ),
  ),

  body: new RefreshIndicator(
    child: BlocProviderTree(
        blocProviders: [
          PostProvider<PostBloc>(bloc: _postBloc)

        ],
        child: BlocBuilder(
          bloc: _postBloc,
          builder: (BuildContext context, PostState state) {
          ....

  }

【问题讨论】:

  • 移除 State 类中的 final int postid; 并使用 widget.postid。详情请查看我的回答。

标签: flutter bloc


【解决方案1】:

走了不同的路线并让它发挥作用。使用过:

_postBloc.dispatch(Fetch(postid: postid));

将其发送到事件。

然后简单地在事件本身中声明它,然后在进行 api 调用时可以在 event.postid 中访问它。

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2020-02-02
    • 2020-12-01
    • 2021-01-27
    • 2021-11-15
    • 1970-01-01
    • 2018-10-21
    • 2022-01-26
    相关资源
    最近更新 更多