Flutter PageView无法在web上滑动(桌面模式)



我是新手。我在其文档的帮助下实现了flutter PageView:

/// Flutter code sample for PageView
// Here is an example of [PageView]. It creates a centered [Text] in each of the three pages
// which scroll horizontally.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
/// This is the stateless widget that the main application instantiates.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final PageController controller = PageController(initialPage: 0);
return PageView(
/// [PageView.scrollDirection] defaults to [Axis.horizontal].
/// Use [Axis.vertical] to scroll vertically.
scrollDirection: Axis.horizontal,
controller: controller,
children: const <Widget>[
Center(
child: Text('First Page'),
),
Center(
child: Text('Second Page'),
),
Center(
child: Text('Third Page'),
)
],
);
}
}

我在安卓系统上运行,效果很好。它也可以在web(移动模式)。

但是当我在chrome (web|桌面)上运行它时,页面是不可滑动的,并且没有办法改变页面。

如何在web桌面导出上启用滑动?

Flutter版本为2.5.2

感谢Bigfoot,为了支持鼠标滑动,我们需要通过以下步骤改变应用程序的默认滚动行为:

1-创建一个类,从MaterialScrollBeavior扩展它,并覆盖dragDevices:

class AppScrollBehavior extends MaterialScrollBehavior {
@override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
};
}

2-将AppScrollBehavior实例传递给MaterialApp的scrollBehavior属性:

MaterialApp(
scrollBehavior: AppScrollBehavior(),
...
);

之后,我们也可以用鼠标在页面之间滑动。

Update Flutter 3.3:

从flutter 3.3,笔记本电脑上的触控板不工作的滚动和滑动动作,如果你需要支持触控板,你需要添加PointerDeviceKind.trackpaddragDevices像这样:

class AppScrollBehavior extends MaterialScrollBehavior {
@override
Set<PointerDeviceKind> get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
PointerDeviceKind.trackpad,
};
}

在flutter 2.5.0中,它们改变了滚动行为检查这个默认拖动滚动设备

无需创建额外的类和其他东西,您可以这样做:

ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(
dragDevices: {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
},
),
child: MyScrollableWidget(...)

我在我的Flutter投资组合网站中使用了PageView。我注意到我不能滑动来换页。后来我才知道,这可以通过Mac的触控板手势来实现。由于PageView是水平的,我必须在触控板上水平滑动两个手指。你可以试试。

最新更新