Warm tip: This article is reproduced from serverfault.com, please click

flutter-Widget和CupertinoWidget:避免代码重复

(flutter - Widget and CupertinoWidget : avoid code duplicate)

发布于 2020-11-27 17:37:50

当我们想要适用于Android的特定于平台的Widget和适用于iOS的Cupertino Widget(如Switch)时,如何避免代码重复?

       @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(),
            body: (Platform.isAndroid)
                ? Switch(
                   value: activate,
                   onChanged: (value) {
                    setState(() {
                      activate = value;
                    });
                   },
                 )
                : CupertinoSwitch(
                   value: activate,
                   onChanged: (value) {
                    setState(() {
                     activate = value;
                    });
                   },
                 )
              );
             }
Questioner
Captain Web
Viewed
11
Captain Web 2020-11-28 08:05:29

终于有人给了我解决方案。我们可以使用构造器“ .adaptive()”,该构造器可用于某些Cupertino小部件,例如Switch或Sliders:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Switch.adaptive(
              value: activate,
              onChanged: (value) {
                setState(() {
                  activate = value;
                });
              },
         )
    );
  }

https://api.flutter.dev/flutter/material/Switch/Switch.adaptive.html

如果我们查看Flutter中的Switch.adaptive构建方法,可以看到它将通过以下方式为我们检查PLatform: Theme.of(context).platform