What is the difference between didChangeDependencies and initState?

后端 未结 8 935
刺人心
刺人心 2021-01-31 17:09

I am new to flutter and when I want to call my context in InitState it throws an error : which is about BuildContext.inheritFromWidgetOfExactType but then I use did

相关标签:
8条回答
  • 2021-01-31 18:13

    This is a supplemental answer showing what the OP described.

    The State class of a StatefulWidget has a context property. This build context is first available in didChangeDependencies. Trying to use context in initState will cause an error.

    class HomeWidget extends StatefulWidget {
      const HomeWidget({Key key}) : super(key: key);
    
      @override
      _HomeWidgetState createState() => _HomeWidgetState();
    }
    
    class _HomeWidgetState extends State<HomeWidget> {
      @override
      void initState() {
        print('initState');
        // print(Theme.of(context));        // ERROR!
        super.initState();
      }
    
      @override
      void didChangeDependencies() {
        print('didChangeDependencies');
        print(Theme.of(context));           // OK
        super.didChangeDependencies();
      }
    
      @override
      Widget build(BuildContext context) {
        print('build');
        print(Theme.of(context));           // OK
        return Container();
      }
    }
    

    Running that gives the print statements in the following order:

    initState
    didChangeDependencies
    ThemeData#93b06
    build
    ThemeData#93b06
    

    See also Working with didChangeDependencies() in Flutter

    0 讨论(0)
  • 2021-01-31 18:13

    The answer is here

    This method should not be called from widget constructors or from State.initState methods, because those methods would not get called again if the inherited value were to change. To ensure that the widget correctly updates itself when the inherited value changes, only call this (directly or indirectly) from build methods, layout and paint callbacks, or from State.didChangeDependencies.

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