在 TabBar 中以编程方式处理 PageViewer 的滑动 - Flutter

Handle swipe of PageViewer Programmatically in TabBar - Flutter

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

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

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

但是当我从第3个标签滑动到第1个标签时,页面出现的顺序是这样的:

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

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

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

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

您可以跟踪上一个标签索引。使用它来呈现综合浏览量的初始页面。请参考以下代码示例。

Tabbar 包含小部件,

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')),
          ],
        ),
      ),
    );
  }
}

综合浏览量包括第二个标签小部件,

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')),
      ],
    );
  }
}

希望你能从中得到启发。