Widget and CupertinoWidget : avoid code duplicate

Issue

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;
                    });
                   },
                 )
              );
             }

Solution

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

Answered By – Florian K

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.