is there any difference between assigning value to the variable inside of initState or not in Flutter StatefulWidget?

后端 未结 1 827
离开以前
离开以前 2021-01-19 03:25

I saw two ways to declare variables with StatefulWidget in many sample codes.

  1. initialize variable with value (firstCase)
  2. initialize v
相关标签:
1条回答
  • 2021-01-19 04:25

    If you can create initialise your variable directly in the property, do so. It's better for readability (a single place to look for).

    The only reason you'll want to use initState is for when you cannot initialise the variable directly from its declaration.

    These situations are for the most part:

    • your variable depends on widget or context
    • it depends on this

    For example, if you want to create an AnimationController you'll need to pass it vsync: this. But the following won't compile:

    class MyState extends State with SingleTickerProviderStateMixin {
      final myController = AnimationController(
        vsync: this, // compile error, cannot use `this` on initialisers
      );
    }
    

    And you'd have to instead write:

    class MyState extends State with SingleTickerProviderStateMixin {
      AnimationController myController;
    
      @override
      void initState() {
        super.initState();
        myController = AnimationController(
          vsync: this, // OK
        );
      }
    }
    

    Although note that this specific example will soon change as a future version of Dart will introduce the late keyword, which then allows:

    class MyState extends State with SingleTickerProviderStateMixin {
      late final myController = AnimationController(
        vsync: this, // OK, not a compile error this time
      );
    }
    

    You may still need initState for variables that depends on widget/context though.

    0 讨论(0)
提交回复
热议问题