首页 > 解决方案 > 在 TabBar 中以编程方式处理 PageViewer 的滑动 - Flutter

问题描述

我已经实现TabBar了 3 个选项卡。在第二个选项卡中,该类包含PageViewer及其 3 页。

现在,当我从第一个选项卡滑动到第三个选项卡时,页面出现的顺序是这样的:

1st Tab >> 
2nd Tab(PageViewer index 0th page) > (index 1st page) > (index 2nd page) >> 
3rd Tab.

但是当我从 3rd Tab 滑动到 1st Tab 时,页面出现的顺序是这样的:

3rd Tab >>
2nd Tab(PageViewer index 0th page) >>
1st Tab.

当我从第三个选项卡转到第一个选项卡时,我想要的是:

3rd Tab >>
2nd Tab(PageViewer index 3rd page) > (index 2nd page) > (index 1st page) >>
1st Tab.

我正在寻找可以有代码示例或手势处理的解决方案。

标签: flutternavigationgesturetabbarflutter-pageview

解决方案


You can keep the track of the previous tab index. Use that to render the pageview's initial page. Refer following code sample.

Tabbar included widget,

class MyTabbedPage extends StatefulWidget {
  const MyTabbedPage({Key key}) : super(key: key);
  @override
  _MyTabbedPageState createState() => _MyTabbedPageState();
}
class _MyTabbedPageState extends State<MyTabbedPage> with SingleTickerProviderStateMixin {
  TabController _tabController;
  // keeps the track of tab index
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
    _tabController.addListener(_handleTabSelection);
  }

  _handleTabSelection() {
    setState(() {
      if (_tabController.index != 1) _currentIndex = _tabController.index;
    });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            controller: _tabController,
            tabs: [
              Tab(text: 'Tab 1'),
              Tab(text: 'Tab 2'),
              Tab(text: 'Tab 3'),
            ],
          ),
          title: const Text('Tabs Demo'),
        ),
        body: TabBarView(
          controller: _tabController,
          children: [
            Center(child: Text('Tab 1')),
            SecondTab(tabIndex: _currentIndex),
            Center(child: Text('Tab 3')),
          ],
        ),
      ),
    );
  }
}

Pageview included second tab widget,

class SecondTab extends StatelessWidget {
  final int tabIndex; // tab index, which came from
  SecondTab({Key key, @required this.tabIndex}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // set initial page to first or last based on previous tab index
    final PageController controller = PageController(initialPage: tabIndex);

    return PageView(
      scrollDirection: Axis.horizontal,
      controller: controller,
      children: const <Widget>[
        Center(child: Text('First Page')),
        Center(child: Text('Second Page')),
        Center(child: Text('Third Page')),
      ],
    );
  }
}

I hope you can get an idea from this.


推荐阅读