skip to Main Content
late State<MyHomePage> myHomePageState;

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() {
     myHomePageState = _MyHomePageState();
     return myHomePageState;
  }
}

One concern: if state is reused and the method createState() is not called. is it possible?

2

Answers


  1. Technically this is not recommended. It will be very unpredictable and additionally, "createstate" is not really meant to be used like this and will probably crash. It might work under some circumstances (or for some issues) but it isn’t intended so the chances of your code breaking will be high and any deviation from set cases will crash your app or do something worse.

    TLDR; Don’t use this.

    Login or Signup to reply.
  2. In Flutter, it’s not safe to hold a reference to the state of a StatefulWidget using a global variable like myHomePageState as you’ve shown in your code. This approach can lead to potential issues and is not a recommended practice.

    Here are some reasons why it’s not considered safe:

    State Reusability:

    Widgets and their associated state can be reused by the Flutter framework as needed. If you store a reference to a specific state, it might not be the correct or current state instance when you access it.

    Memory Leaks:

    Holding references to state objects can lead to memory leaks if those objects are not properly disposed of when they are no longer needed. Flutter handles state disposal automatically, but if you’re storing references, you might interfere with this process.

    Concurrency Issues:

    If you’re accessing the state from multiple places in your code, you might run into concurrency issues, leading to unexpected behavior and crashes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search