Flutter: Changing the current tab in tab bar view using a button

后端 未结 5 1852
北荒
北荒 2020-12-12 15:24

I am creating an app that contains a tab bar on its homepage. I want to be able to navigate to one of the tabs using my FloatingActio

5条回答
  •  长情又很酷
    2020-12-12 16:00

    If you want to jump to a specific page, you can use

    PageController.jumpToPage(int)
    

    However if you need animation, you'd use

    PageController.animateToPage(page, duration: duration, curve: curve)
    

    Simple example demonstrating it.

    // create a PageController
    final _controller = PageController();
    bool _shouldAnimate = true; // whether we animate or jump
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            if (_shouldAnimate) {
              // animates to page1 with animation
              _controller.animateToPage(1, duration: Duration(seconds: 1), curve: Curves.easeOut);  
            } else {
              // jump to page1 without animation
              _controller.jumpToPage(1);
            }
          },
        ),
        body: PageView(
          controller: _controller, // assign it to PageView
          children: [
            FlutterLogo(colors: Colors.orange), // page0
            FlutterLogo(colors: Colors.green), // page1
            FlutterLogo(colors: Colors.red), // page2
          ],
        ),
      );
    }
    

提交回复
热议问题