【发布时间】:2021-05-06 09:10:11
【问题描述】:
在 ios 中,如果我从屏幕左侧开始滑动并朝中心下降,它会从视图中返回。现在我想将 Flutter 中的相同内容复制到我的应用程序中,因为我有左上角的按钮可以返回经典,但我也希望拥有 ios 样式,即使从左侧滑动也可以返回。我该怎么办?
【问题讨论】:
标签: ios flutter controller swipe
在 ios 中,如果我从屏幕左侧开始滑动并朝中心下降,它会从视图中返回。现在我想将 Flutter 中的相同内容复制到我的应用程序中,因为我有左上角的按钮可以返回经典,但我也希望拥有 ios 样式,即使从左侧滑动也可以返回。我该怎么办?
【问题讨论】:
标签: ios flutter controller swipe
查看我使用手势检测器创建的这个示例:
您可以在页面顶部使用此小部件,以便它可以检测到滑动
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FlatButton(
child: Text("Next Page"),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => SecondPage()));
},
),
),
);
}
}
class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(onHorizontalDragUpdate: (details) {
// Note: Sensitivity is integer used when you don't want to mess up vertical drag
int sensitivity = 8;
if (details.delta.dx > sensitivity) {
// Right Swipe
} else if (details.delta.dx < -sensitivity) {
//Left Swipe
Navigator.of(context).pop();
}
}
),
);
}
}
让我知道这就是您要实现的目标
【讨论】:
试过这个并且工作正常,在屏幕 1 上,您正在导航,在您的 手势检测器上添加这一行。
onHorizontalDragUpdate: (details) {
if (details.delta.direction > 0) {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page2()));
}
},
在第 2 页的构建上下文中,添加这一行
onVerticalDragUpdate: (details) {},
onHorizontalDragUpdate: (details) {
if (details.delta.direction <= 0) {
Navigator.pop(context);
}
},
下面是完整的代码sn-p
import 'package:flutter/material.dart';
import 'package:swipe_detection_example/page2.dart';
class Page1 extends StatelessWidget {
const Page1({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onVerticalDragUpdate: (details) {},
onHorizontalDragUpdate: (details) {
if (details.delta.direction > 0) {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page2()));
}
},
child: Scaffold(
body: Center(
child: Text('Page 1'),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:swipe_detection_example/page2.dart';
class Page2 extends StatelessWidget {
const Page2({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onVerticalDragUpdate: (details) {},
onHorizontalDragUpdate: (details) {
if (details.delta.direction <= 0) {
Navigator.pop(context);
}
},
child: Scaffold(
body: Center(
child: Text('Page 2'),
),
),
);
}
}
【讨论】: