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

Widget and CupertinoWidget : avoid code duplicate

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

How to avoid code duplication when we want Platform specific Widget for Android and Cupertino Widget for iOS like 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
0
Captain Web 2020-11-28 08:05:29

Finally someone gave me the solution. We can use constructor ".adaptive()" which is available for some Cupertino Widgets like Switch or 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

if we look at Switch.adaptive build method in Flutter, we can see that it will check the PLatform for us with : Theme.of(context).platform