Home > Back-end >  How can I use initState in a widget build to reference the value of riverpod?
How can I use initState in a widget build to reference the value of riverpod?

Time:09-03

I want to assign the value of currentUser.profilepictureURL to ListImage. But if I put the initState outside of the widget build, it will be out of scope. Please tell me.

    class _MyHomePageState extends ConsumerState<MyHomePage> {
  var listImage = [];
  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(userModelProvider);
    void initState() {
      listImage.add(currentUser.profilePictureURL);
      super.initState();
    }
    return Container();
  }
}

CodePudding user response:

The way your are using initState is wrong. InitState is an @override and it should not to be used inside a build method.

try this:

class _MyHomePageState extends ConsumerState<MyHomePage> {
  var listImage = [];

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(userModelProvider);
    listImage.add(currentUser.profilePictureURL);
    return Container();
  }
}
  • Related