How to manage native looks of switch widget in flutter

三世轮回 提交于 2020-12-13 03:41:46

问题


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:

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

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


回答1:


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



回答2:


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()


来源:https://stackoverflow.com/questions/58319811/how-to-manage-native-looks-of-switch-widget-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!