Flutter PageView 检查页面是否使用拖动手势或 animateToPage() 改变
Flutter PageView check if page changed using drag gesture or animateToPage()
在具有类似以下结构的脚手架页面中
@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()
功能改变的?
谢谢。
也许您可以添加一个标志来设置 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'),
),
],
),
),
);
}
}
在具有类似以下结构的脚手架页面中
@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()
功能改变的?
谢谢。
也许您可以添加一个标志来设置 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'),
),
],
),
),
);
}
}