import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('单选开关(Switch)'),
),
body: Center(
child: SwitchStatefulWidget(),
)
)
);
}
}
class SwitchStatefulWidget extends StatefulWidget {
const SwitchStatefulWidget({Key? key}) : super(key: key);
@override
State<SwitchStatefulWidget> createState() => _SwitchStatefulWidget();
}
class _SwitchStatefulWidget extends State<SwitchStatefulWidget> {
bool _switchSelected=true; //维护单选开关状态
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
"1. 单选开关",
textScaleFactor: 1.2,
),
Switch(
value: _switchSelected,//当前状态
onChanged:(value){
//重新构建页面
setState(() {
_switchSelected = value;
});
},
),
Text(
"2. IOS 风格单选开关",
textScaleFactor: 1.2,
),
CupertinoSwitch(
value: _switchSelected,
onChanged: (value) {},
),
Text(
"3. SwitchListTile",
textScaleFactor: 1.2,
),
SwitchListTile(
secondary: const Icon(Icons.shutter_speed),
title: const Text('硬件加速'),
value: _switchSelected,
onChanged: (bool value) {
setState(() {
_switchSelected = !_switchSelected;
});
},
),
],
);
}
}