Dart 层如何 兼容 Android 和iOS平台特性 ,阿里大神最佳总结Flutter进阶学习笔记
在Flutter中,为了在不同平台上编写具有特殊逻辑的代码,可以使用dart:io
库来检查当前是Android还是iOS平台,或者使用package_info_plus
插件来获取应用的包信息。
以下是一个简单的例子,演示如何根据平台特性来调整代码:
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PlatformSpecificWidget(),
);
}
}
class PlatformSpecificWidget extends StatefulWidget {
@override
_PlatformSpecificWidgetState createState() => _PlatformSpecificWidgetState();
}
class _PlatformSpecificWidgetState extends State<PlatformSpecificWidget> {
String _platformVersion = 'Unknown';
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
if (kIsWeb) {
platformVersion = 'Web';
} else {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
platformVersion = packageInfo.buildNumber;
if (Theme.of(context).platform == TargetPlatform.iOS) {
platformVersion += 'iOS';
} else {
platformVersion += 'Android';
}
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Platform Specific Widget'),
),
body: Center(
child: Text('Running on $_platformVersion\n'),
),
);
}
}
在这个例子中,我们使用kIsWeb
来检查是否在Web平台上运行,然后使用PackageInfo.fromPlatform()
来获取应用的版本号。接着,我们检查当前的Theme.of(context).platform
来判断是iOS还是Android平台,并相应地给_platformVersion
赋值。最后,在界面上显示当前平台的信息。这样,无论是在Android设备还是iOS设备上,用户都能看到特定于他们平台的个性化信息。
评论已关闭