Skip to content

Instantly share code, notes, and snippets.

@ChangJoo-Park
Created February 6, 2020 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChangJoo-Park/9076444bef4f6b77d48d8bb3c8ad9ae1 to your computer and use it in GitHub Desktop.
Save ChangJoo-Park/9076444bef4f6b77d48d8bb3c8ad9ae1 to your computer and use it in GitHub Desktop.
platform aware switch widget
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
PlatformSwitch(platform: 'cupertino'),
PlatformSwitch(),
],
),
),
);
}
}
/// [PlatformSwitch] 는 각 플랫폼에 맞는 스위치 위젯을 렌더링합니다.
/// 이 에제에서는 [platform] 이라는 String 속성을 사용하지만,
/// 실제 프로젝트에서 사용할 때는 `import 'dart:io' show Platform;` 라이브러리를 이용하여야합니다.
/// 사용방법은 [Platform.isAndroid] 또는 [Platform.isIOS] 로
/// 해당 플랫폼에 맞는 [build] 메소드를 구현해야합니다.
class PlatformSwitch extends StatefulWidget {
final String platform;
PlatformSwitch({this.platform});
@override
_PlatformSwitchState createState() => _PlatformSwitchState();
}
class _PlatformSwitchState extends State<PlatformSwitch> {
bool _value = false;
ValueChanged<bool> _onChanged;
@override
Widget build(BuildContext context) {
if (widget.platform == 'cupertino') {
return CupertinoSwitch(value: _value, onChanged: onChanged);
}
return Switch(value: _value, onChanged: onChanged);
}
onChanged(bool value) {
setState(() {
_value = value;
});
_onChanged(_value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment