近期尝试将自己的Flutter运行在Web页面上,可谓是一波三折,不过最终还是运行成功,在这里记录一下遇到的问题。
-
Platform
兼容报错:Unsupported operation: Platform._operatingSystem
。
原因:应该是Platform.isIOS
、Platform.isAndroid
等不支持Web。
解决:搜索后最终在Github上这个 flutter issue 找到了解决办法。在
pubspec.yaml
引入这个依赖:universal_platform: ^1.0.0+1
在用到
Platform.isIOS
等地方替换成UniversalPlatform.isIOS
,或者用自定义的类包装一下供全局使用。import 'package:universal_platform/universal_platform.dart'; class DeviceUtil { static bool get isDesktop => !isWeb && (isWindows || isLinux || isMacOS); static bool get isMobile => isAndroid || isIOS; static bool get isWeb => UniversalPlatform.isWeb; static bool get isWindows => UniversalPlatform.isWindows; static bool get isLinux => UniversalPlatform.isLinux; static bool get isMacOS => UniversalPlatform.isMacOS; static bool get isAndroid => UniversalPlatform.isAndroid; static bool get isFuchsia => UniversalPlatform.isFuchsia; static bool get isIOS => UniversalPlatform.isIOS; }
使用:
bool isMobile = DeviceUtil.isMobile
-
跨域问题:
DioError [DioErrorType.response]: XMLHttpRequest error.
。
原因:Flutter运行在浏览器上是localhost:xxxx
,而我们的API接口是xxxx.com
,两个不在同一个域名下不能直接访问跨域资源,关于为什么会存在跨域问题,网上有很多的资料,感兴趣的可以看看这篇文章。解决方法分两种:
-
本地解决办法,参考 stackoverflow 上的。
a. 删除flutter\bin\cache
目录下的flutter_tools.stamp
文件。
b. 打开flutter\packages\flutter_tools\lib\src\web
目录下的chrome.dart
文件。
c. 在chrome.dart
中找到--disable-extensions
一行,在其下方添加--disable-web-security
。改好运行后的结果如下:
-
服务端解决方法,如果Web端需要上线,这种也是最终解决方案,当然需要和后端的兄弟沟通好。
'Access-Control-Allow-Origin': '*' 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE' // If needed 'Access-Control-Allow-Headers': 'X-Requested-With,content-type' // If needed 'Access-Control-Allow-Credentials': true // If needed
-
-
报错:
The provided ScrollController is currently attached to more than one ScrollPosition.
解决:在
ListView
等Widget
上加controller: ScrollController()
解决。ListView.separated( shrinkWrap: true, controller: ScrollController(), itemCount: .., itemBuilder: (context, index) { return ...; }, separatorBuilder: (BuildContext context, int index) { return ...; }, )
你的Flutter
代码在Web端运行遇到过哪些问题呢?欢迎👏🏻在评论区交流一下!