Widget and CupertinoWidget : avoid code duplicate

221 views Asked by At

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

There are 2 answers

0
Florian K On BEST ANSWER

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

1
Alex Radzishevsky On

I often like to wrap "standard" widgets with my own widgets - it allows you to control them in once place. And as side benefit - makes code duplication only in those Widget classes.

Also I see potential to move out onChanged function and assign it two times to onChanged field of the widget, like this:

@override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(),
            body: (Platform.isAndroid)
                ? Switch(
                   value: activate,
                   onChanged: _handleChange,
                 )
                : CupertinoSwitch(
                   value: activate,
                   onChanged: _handleChange,
                 )
              );
             }

void _handleChange() => setState(() { activate = value; });