Flutter: unexpected behavior using package ConvexBottomBar

26 Views Asked by At

I am using ConvexBottomBar as my package for the bottom navigation bar. I have 2 problems, and the solutions for them are incompatible:

  1. There is no selectedIndex, so when I change the page manually (sliding left or right), the tab bar would not update.

To solve this, I added an onChanged() method that updates the tab bar when each view gets visible:

void _onPageChanged(int index) {
    _appBarKey.currentState!.tap(index);
  }
  1. It is not possible to move directly from index 0 to 2, or vice-versa. As the page tab updates when the view in the center gets shown, it sets the tab to be in index 1.

The solution for this would be removing the onChanged() method, but then the tab would not update.

It seems to me that the solutions for both bugs are incompatible. But there should be something I am able to do. This is my whole widget state:

class GameShellViewState extends State<GameShellView> {
  final PageController _pageController = PageController(initialPage: 1);

  void _onPageChanged(int index) {
    _appBarKey.currentState!.tap(index);
  }

  void _onTap(int index) {
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      body: PageView(
        controller: _pageController,
        onPageChanged: _onPageChanged,
        children: const [
          CareerView(),
          EducationView(),
          VidaView(),
        ],
      ),
      bottomNavigationBar: ConvexAppBar(
        key: _appBarKey,
        elevation: 0,
        style: TabStyle.reactCircle,
        items: const [
          TabItem(icon: Icons.work, title: 'Career'),
          TabItem(icon: Icons.school, title: 'Education'),
          TabItem(icon: Icons.heart_broken, title: 'Vida'),
        ],
        initialActiveIndex: 2,
        onTap: _onTap,
        backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
        activeColor: Theme.of(context).colorScheme.primary,
        color: Theme.of(context).colorScheme.primary,
      ),
    );
  }
}
1

There are 1 best solutions below

0
Temo Fey On

Both the _onPageChanged() and _onTap() methods require an int index, so we can replace the 2 methods with one:

_changePage(int index){
  _appBarKey.currentState!.tap(index);
  _pageController.animateToPage(index,
    duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
}

And then use this method in PageView

Scaffold(
  extendBody: true,
  body: PageView(
    controller: _pageController,
    onPageChanged: _changePage,
    ...
  ),

and ConvexAppBar:

bottomNavigationBar: ConvexAppBar(
    ...
    onTap: _changePage,
    ...
  ),