Flutter State Management using InheritedWidget for Journal App - No Packages

Поделиться
HTML-код
  • Опубликовано: 24 янв 2025

Комментарии •

  • @George-or3uv
    @George-or3uv 2 года назад

    I have been looking at your code. I was wondering, because you said that the state can only be used inside the widget tree (from parent to child || children), can we use the state of the inheritedWidget if it is used with push navigations ( i.e. pressing a button to Navigate to a new Scaffold)? What would be an example of when we couldn't use an InheritedWidget due to it being outside of the scope of the Widget tree? Am I correct in thinking that it can't be used in certain situations? Hopefully I am being clear.

    • @JediPixels
      @JediPixels  2 года назад

      The entire application is a big widget tree starting at the root when runApp(MyApp()) is called from the main() method in the main.dart file. You can place the InheritedWidget in your main.dart file wrapping the Home() page. It will make it available to all child widgets.
      If I understand your question correctly, wherever you place the InheritedWidget any widgets above will not have access to it, but all of the widgets below will. If you try to access the InheritedWidget from a widget above you will get a Unexpected null value error.
      You can use the InheritedWidget with the Navigator like this:
      Navigator.of(context).push(
      MaterialPageRoute(
      builder: (context) => const AppState(
      moods: 'Happy',
      child: MyPage(),
      ),
      ),
      );
      In the MyPage() you access the InheritedWidget like this:
      @override
      void didChangeDependencies() {
      super.didChangeDependencies();
      AppState appState = AppState.of(context)!;
      debugPrint('appState: ${appState.moods}');
      }