zerochill
zerochill

Reputation: 746

How can I stop my future builders to reload when I switch back to the tab again? - Flutter/dart

I am using a bottom navigation bar and every tab has a future builder and every time I switch to the next tab and switch back to the old one it reloads back

class LandingPage extends StatefulWidget {
  @override
  _LandingPageState createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  int _selectedIndex = 1;

  static List<Widget> _widgetOptions = <Widget>[
    //Home
    HomePage(),

    //Search
    PostGridScreen(),

    //Favourites
    Text(
      'Index 1: Favourites',
    ),

    //Post
    AddPost(),

    //Index 4: Profile
    Profile(),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          //Home
          BottomNavigationBarItem(
            icon: Icon(Icons.pets),
            label: 'Shop',
          ),

          //Search
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Search',
          ),

          //Favourites
          BottomNavigationBarItem(
            icon: Icon(Icons.favorite),
            label: 'Favourites',
          ),

          //Post
          BottomNavigationBarItem(
            icon: Icon(Icons.add_box),
            label: 'Post',
          ),

          //Profile
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.black,
        selectedFontSize: 14,
        onTap: _onItemTapped,
      ),
    );
  }
}

In the PostGridScreen() when I tap on a grid it gets me on the detail page and when I come back to the grid screen the data doesn't reload, but when I switch the tabs of my bottom navigation bar the data reloads and the future builders reload. Till now I have tried everything and I don't know what to do. Please Help.

Upvotes: 0

Views: 1156

Answers (1)

mkobuolys
mkobuolys

Reputation: 5333

You can try using the AutomaticKeepAliveClientMixin (https://api.flutter.dev/flutter/widgets/AutomaticKeepAliveClientMixin-mixin.html) and overriding the wantKeepAlive to return true, also adding the super.build(context) at the beginning of build method. This way, the state is persisted when navigating between tabs.

I have only used this with PageView.builder() and not your way (swapping child inside the Center widget based on tab index), so you just need to try that out, it may or may not work.

Upvotes: 1

Related Questions