Page started at begin when navigate between 2 screen using BottomTabNavigator

Issue

I am new at Flutter. I started a new project regarding social media. I used BottomTabNavigation for navigating the Home screen to the notification screen. Now the problem is that when I am showing feeds on the home page and I scroll down at many posts. let’s say I am on post number 50. Now when I click on the notification and again click on the Home page its started from begin. I need to stay my scroll at a previous position on every main screen.

Here is my code for navigating one page to another.

class _DefaultLayoutWidgetState extends State<DefaultLayoutWidget> {
  final List<Map<String, dynamic>> _pages = [
    {'page': PostScreen(), 'title': 'SelfieCorner'},
    {'page': NotificationScreen(), 'title': 'Notifications'}
  ];

  int _curruntIndex = 0;

  void handleTapEvent(inx) {
    setState(() {
      _curruntIndex = inx;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PostAppBarWidget(),
      body: _pages[_curruntIndex]['page'],
      bottomNavigationBar: BottomNavigationBar(
        onTap: (index) => handleTapEvent(index),
        currentIndex: _curruntIndex,
        items: [
          BottomNavigationBarItem(
            icon: Icon(
              Icons.home,
            ),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.notifications,
            ),
            title: Text('Notifications'),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.lock,
            ),
            title: Text('Profile'),
          )
        ],
      ),
    );
  }
}

Solution

Consider using IndexedStack like this. It will save the state of the previous widget while moving to another.

body: IndexedStack(.....),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (index) => handleTapEvent(index),
        currentIndex: _curruntIndex,
        items: [
          BottomNavigationBarItem(
            icon: Icon(
              Icons.home,
            ),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.notifications,
            ),
            title: Text('Notifications'),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.lock,
            ),
            title: Text('Profile'),
          )
        ],
      ),

Answered By – Amon Chowdhury

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.