在 ios 中,如果我从屏幕左侧开始滑动并落向中心,它就会从视图中返回。现在我想在 Flutter 中将同样的事情复制到我的应用程序中,因为我有左上角的按钮可以返回经典,但我也希望有 ios 风格,您甚至可以通过从左侧滑动来返回。我该怎么办?
查看我使用手势检测器创建的示例:
您可以在页面顶部使用此小部件,以便它可以检测滑动
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);
}
},
完整代码片段如下
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'),
),
),
);
}
}
从 Flutter 版本 3.22.2 开始,您可以通过添加以下代码来启用预测后退手势:
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
// Set the predictive back transitions for Android.
TargetPlatform.android: PredictiveBackPageTransitionsBuilder(),
},
),
),
...
),