0

我正在尝试在颤动中创建一个 BottomNavigationBar,但我想禁用页面之间的幻灯片动画。如果我从第一个选项卡转到第三个选项卡,我希望它直接打开第三个选项卡,而不是通过第二个选项卡然后滑动到第三个选项卡。

这是我的代码:

class MyApp3 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState3();
  }
}

class _MyAppState3 extends State<MyApp3> {
  @override
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
  }

  @override
  Widget build(BuildContext context) {
    var pages = [FirstTab(), SecondTab(), ThirdTab()];

    var pageView = PageView(
      controller: _pageController,
      physics: NeverScrollableScrollPhysics(),
      children: pages,
    );

    var bottomNav = BottomNavigationBar(
      onTap: (tabIndex) {
        _pageController.jumpToPage(tabIndex);
      },
      items: [
        BottomNavigationBarItem(icon: Icon(Icons.home), label: "Start"),
        BottomNavigationBarItem(
            icon: Icon(Icons.camera_enhance), label: "Second"),
        BottomNavigationBarItem(icon: Icon(Icons.offline_pin), label: "Home"),
      ],
    );

    return MaterialApp(
        home: Scaffold(
      body: pageView,
      bottomNavigationBar: bottomNav,
    ));
  }
}

使用此代码,一切都可以按我的意愿进行,但是当页面更改时,BottomNavigationBarItem 不会更改。它总是这样:

我该怎么做才能使 BottomNavigationBarItem 选择更改?

4

1 回答 1

1

尝试这个。

class MyApp3 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState3();
  }
}

class _MyAppState3 extends State<MyApp3> {
  @override
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
  }

  int _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    var pages = [FirstTab(), SecondTab(), ThirdTab()];

    var pageView = PageView(
      controller: _pageController,
      physics: NeverScrollableScrollPhysics(),
      children: pages,
    );

    var bottomNav = BottomNavigationBar(
      onTap: (tabIndex) {
         setState((){_currentIndex = tabIndex;});
        _pageController.jumpToPage(tabIndex);
      },
      currentIndex: _currentIndex,
      items: [
        BottomNavigationBarItem(icon: Icon(Icons.home), label: "Start"),
        BottomNavigationBarItem(
            icon: Icon(Icons.camera_enhance), label: "Second"),
        BottomNavigationBarItem(icon: Icon(Icons.offline_pin), label: "Home"),
      ],
    );

    return MaterialApp(
        home: Scaffold(
      body: pageView,
      bottomNavigationBar: bottomNav,
    ));
  }
}
于 2020-08-31T11:54:35.523 回答