Flutter 是否在 iOS 中自动显示 Cupertino UI,在 Android 中使用单一代码库显示 Materials?

我需要知道 Flutter 是否会在 iOS 上渲染 iOS Cupertino 风格,在 Android 上渲染 Material 风格,只需要一个代码库。在开始用 Flutter 开发我的应用程序之前,我想知道这一点。

如果不是,我将如何在一个代码中管理两个不同的 UI?我不可能在代码的任何地方使用 if/else。

39277 次浏览

These capabilities are under development. I suggest to look into this library: https://pub.dartlang.org/packages/flutter_platform_widgets

Other than that, there is a lot you can do already, even without this library. Everything depends on your resources, requirements and complexity of your project.

For example, if you are working alone or in a small team, your project's complexity is probably not overwhelming, and your entire application will consist only of a couple of dozens of Widget derived classes at max. In this case, maybe you can deliberately program the platform-adaptive behavior in your custom Widget classes, so that you'll be happy working with them long-term.

This workflow is not always applicable, and may seem complicated at the beginning, but it will become more natural later.

You should try the gallery app: https://play.google.com/store/apps/details?id=io.flutter.demo.gallery&hl=en In there, when you press the menu button you can set platform mechanics to be Mountain View (Android) or Cupertino (iOS). That way you can see how it's going to look in either platform.

Here is an example of selecting Cupertino or Material with code depending on the platform: https://medium.com/flutter-io/do-flutter-apps-dream-of-platform-aware-widgets-7d7ed7b4624d As far as I know you have to choose the widgets like this.

As of recently, Flutter has added adaptive constructors for Switch, SwitchListTile, and CircularProgressIndicator which will help further progress platform-aware widgets within a single codebase. While these are the only three as of now, expect more in the future!

Below simple implementation:

class AdaptiveSwitch extends StatelessWidget {
const AdaptiveSwitch({Key key,
@required this.value,
@required this.onChanged,
this.activeColor,
this.dragStartBehavior = DragStartBehavior.start})
: assert(dragStartBehavior != null),
super(key: key);


final bool value;


final ValueChanged<bool> onChanged;


final Color activeColor;


final DragStartBehavior dragStartBehavior;


@override
Widget build(BuildContext context) {
return Theme.of(context).targetPlatform = TargetPlatform.iOS
? CupertinoSwitch(
value: value,
activeColor: activeColor,
onChanged: onChanged,
dragStartBehavior: dragStartBehavior,
)
: Switch(
value: value,
activeColor: activeColor,
onChanged: onChanged,
dragStartBehavior: dragStartBehavior,
);
}
}