Home > Software design >  How can I create an animation for the bottom navigation bar in Flutter?
How can I create an animation for the bottom navigation bar in Flutter?

Time:05-07

I have a bottom navigation bar with some tabs and I want to animate the icons of them when I switch page, without an external package.

And I have one more question, I added a view pager to switch pages swiping, and taping in the nav bar icons, but I got an error. For example: I am in the page 1, and I want to switch to page 3, while it is going and passes page 2, it goes back and stay in page 2.

_onPageChanged method:

_onPageChanged(int index) {
  setState(() {
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 200), curve: Curves.easeInOut);

    _activePage = index;
  });
}

BottomNavBar(from scratch) and ViewPager:

bottomNavigationBar: BottomNavBar(
  activeTab: _activePage,
  onTabTap: _onPageChanged,
  tabs: const [
    BottomNavBarItem(
      icon: Icon(Icons.icon_1, color: gray),
      selectedIcon: Icon(Icons.icon_1_selected, color: white)
    ),
    BottomNavBarItem(
      icon: Icon(Icons.icon_2, color: gray),
      selectedIcon: Icon(Icons.icon_2_selected, color: white)
    ),
    BottomNavBarItem(
      icon: Icon(Icons.icon_3, color: gray),
      selectedIcon: Icon(Icons.icon_3_selected, color: white)
    ),
  ],
),
body: PageView(
  controller: _pageController,
  onPageChanged: _onPageChanged,
  children: _pages,
),

CodePudding user response:

The BottomNavigationBarItem's icon parameter is a Widget, so you can use any Widget you'd like for what you have in mind, this is not related to the NavigationBar, but rather to what you'd like to animate.

So it could be as simple as an icon rotating once it's been clicked.

class AnimatedButtonThingy extends StatefulWidget {
  const AnimatedButtonThingy({Key? key}) : super(key: key);

  @override
  _AnimatedButtonThingyState createState() => _AnimatedButtonThingyState();
}

class _AnimatedButtonThingyState extends State<AnimatedButtonThingy>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  bool shouldAnimate = false;

  @override
  void initState() {
    _controller =
        AnimationController(vsync: this, duration: Duration(seconds: 2));
          
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          setState(() {
            shouldAnimate = !shouldAnimate;
            shouldAnimate ? _controller.repeat() : _controller.stop();
          });
        },
        child: Icon(Icons.auto_awesome));
  }
}

Read the code above as pseudo-code, since it has not been tested, but give you an idea what could be done. The animation code has been copied from here how-to-rotate-an-image-using-flutter-animationcontroller-and-transform

  • Related