4

I have a widget that I want to recreate the state for what can I do to achieve this? I heard there is a way by UniqueKeys but I have no idea about them well because I'm a beginner (don't worry I have searched)

What I tried so far was to pop the Navigator and then push the same page again... And it works... But the problem is I'm losing the BottomNavigationBar when doing that as my page gets out of the state...

Here is my approach to solving this problem so far


@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.inactive ||
        state == AppLifecycleState.paused) {
      Navigator.pop(context);
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => Home()));
    }
    super.didChangeAppLifecycleState(state);
  }


BottomNavigationBar


int _selectedItem = 0;
  PageController pageController;

  void _onPageChanged(int pageIndex) {
    setState(() {
      _selectedItem = pageIndex;
    });
  }

  void _onTapped(int pageIndex) {
    setState(() {
      _selectedItem = pageIndex;
    });
    pageController.jumpToPage(pageIndex);
  }

  @override
  void initState() {
    pageController = PageController();
    super.initState();
  }

  @override
  void dispose() {
    pageController.dispose();
    super.dispose();
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: pageController,
        children: pages,
        onPageChanged: _onPageChanged,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: bottomNavigationBarItems(context), // You can find this below
        currentIndex: _selectedItem,
        onTap: _onTapped,
      ),
    );
  }
}


bottomNavigationBarItems


List<BottomNavigationBarItem> bottomNavigationBarItems(BuildContext context) {
  final AppLocalization translate = AppLocalization.of(context);
  final BottomNavigationBarItem homePage = BottomNavigationBarItem(
    icon: FaIcon(FontAwesomeIcons.home),
    label: translate.translate('home'),
  );

  final BottomNavigationBarItem newsPage = BottomNavigationBarItem(
    icon: FaIcon(FontAwesomeIcons.newspaper),
    label: translate.translate('news'),
  );

final BottomNavigationBarItem programsPage = BottomNavigationBarItem(
    icon: FaIcon(FontAwesomeIcons.tv),
    label: translate.translate('programs'),
  );
 return [
    homePage,
    newsPage,
    programsPage,
  ];
}

1 Answers1

2

any widget give it

key: UniqueKey(),

will lose current states when setState called and rebuild again

hasd11
  • 135
  • 1
  • 10