【问题标题】:Flutter PageView check if page changed using drag gesture or animateToPage()Flutter PageView 检查页面是否使用拖动手势或 animateToPage() 更改
【发布时间】:2021-04-18 01:18:39
【问题描述】:

在具有类似以下结构的 Scaffold 页面中

@override
Widget build(BuildContext context){
  body: PageView(
          controller: _controller;
          children: <Widget>[Page1(), Page2(), Page3()];
        );
  bottomNavigationBar: BottomNavBar(
                         onItemSelected: (index) => _controller.animateToPage()
                       )
}

Page2()Page1() 有两种方式:

  • 从左向右滑动屏幕
  • 点击bottomNavigationBar上的Page1()图标,从而调用_controller.animateToPage(0)

问题是,如何判断页面是通过滑动手势还是animateToPage()函数改变?

谢谢。

【问题讨论】:

  • PageView 有一个属性onPageChanged。这样就够了吗?
  • 拖动行为和animateToPage()都会触发onPageChanged(index)函数,很难区分。
  • animateToPage() 是你在代码中调用的,其他的不是,你明白我的意思了吗,下面的答案解释了它

标签: flutter flutter-pageview


【解决方案1】:

也许你可以添加一个标志来设置animateToPage 是否正在进行。

示例:

import 'package:flutter/material.dart';

void main() => runApp(Root());

class Root extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final PageController controller = PageController();
    bool isAnimateToPage = false;

    controller.addListener(() {
      print('LISTENER isAnimateToPage = $isAnimateToPage');
    });

    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Expanded(
              child: PageView(
                controller: controller,
                onPageChanged: (int page) {
                  print(
                      'ONPAGECHANGED isAnimateToPage = $isAnimateToPage ; page = $page');
                },
                children: <Widget>[
                  const Center(child: Text('page 1')),
                  const Center(child: Text('page 2')),
                  const Center(child: Text('page 3')),
                ],
              ),
            ),
            FlatButton(
              onPressed: () async {
                isAnimateToPage = true;
                await controller.animateToPage(
                  controller.page.toInt() + 1,
                  duration: const Duration(seconds: 1),
                  curve: Curves.easeIn,
                );
                isAnimateToPage = false;
              },
              child: const Text('Next'),
            ),
          ],
        ),
      ),
    );
  }
}

【讨论】:

  • @StevenLuo 很高兴我能帮上忙。祝你好运!
猜你喜欢
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2014-07-10
相关资源
最近更新 更多