Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage native looks of switch widget in flutter

I want to create switch/toggle widget in Flutter/Dart with native looks of different OS.

I mean if I run on iOS mobile it should be looks like:

enter image description here

If I run on Android mobile it should be looks like :

enter image description here

Help me to achieve this type of functionality in flutter/dart

like image 690
Sanjayrajsinh Avatar asked Oct 10 '19 09:10

Sanjayrajsinh


2 Answers

Use Switch.adaptive

Creates a CupertinoSwitch if the target platform is iOS, creates a material design switch otherwise.

Switch.adaptive(value: true, onChanged: (newValue) {})

Sample code:

bool _value = true;

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(),
    body: Switch.adaptive(
      value: _value,
      onChanged: (newValue) => setState(() => _value = newValue),
    ),
  );
}
like image 108
CopsOnRoad Avatar answered Sep 29 '22 05:09

CopsOnRoad


You can check what platform the user is on and then display the appropriate platform-specific widget. Switch is the Android widget for toggles and CupertinoSwitch is the iOS equivalent. The arguments are the same for both widgets so CopsOnRoad's solution is a bit more succinct but this is another way to get platform-specific widgets.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:io';

Platform.isAndroid ? Switch() : CupertinoSwitch()
like image 26
Karen Avatar answered Sep 29 '22 06:09

Karen