切换选钮,常用于配置的切换,可指定小圆颜色、图片,滑槽颜色等,接收状态变化回调。

相关组件

SwitchListTile CupertinoSwitch

Switch基础用法

  1. <br />【inactiveThumbColor】 : 未选中小圈颜色 【Color】<br />【inactiveTrackColor】 : 未选中滑槽颜色 【Color】<br />【activeColor】 : 选中时小圈颜色 【Color】<br />【activeTrackColor】 : 选中时滑槽颜色 【Color】<br />【onChanged】 : 切换回调 【Function(double)】"<br /> onChanged时,回调true、null、false三种状态<br />![87.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589445713349-1079c279-d50b-4531-a95d-4a9074732f38.gif#align=left&display=inline&height=79&margin=%5Bobject%20Object%5D&name=87.gif&originHeight=79&originWidth=404&size=51276&status=done&style=none&width=404)
import 'package:flutter/material.dart';
class CustomSwitch extends StatefulWidget {
  @override
  _CustomSwitchState createState() => _CustomSwitchState();
}

class _CustomSwitchState extends State<CustomSwitch> {
  final colors = [Colors.red, Colors.yellow, Colors.blue, Colors.green];
  bool _checked = false;

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: colors
          .map((e) =>
          Switch(
              value: _checked,
              inactiveThumbColor: e,
              inactiveTrackColor: Colors.grey.withAlpha(88),
              activeColor: Colors.green,
              activeTrackColor: Colors.orange,
              onChanged: (v) {
                setState(() => _checked = v);
              }))
          .toList(),
    );
  }
}

Switch图片

   <br />【inactiveThumbImage】 : 未选中小圈图片   【ImageProvider】<br />【activeThumbImage】 : 选中时滑槽颜色   【ImageProvider】<br />![88.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589445741624-5b559af8-bc36-4485-9964-05ddeb929110.gif#align=left&display=inline&height=79&margin=%5Bobject%20Object%5D&name=88.gif&originHeight=79&originWidth=404&size=62322&status=done&style=none&width=404)
import 'package:flutter/material.dart';
class ImageSwitch extends StatefulWidget {
  @override
  _ImageSwitchState createState() => _ImageSwitchState();
}

class _ImageSwitchState extends State<ImageSwitch> {
  final imgs = [
    "assets/images/head_icon/icon_5.jpg",
    "assets/images/head_icon/icon_6.jpg",
    "assets/images/head_icon/icon_7.jpg",
    "assets/images/head_icon/icon_8.jpg"];
  bool _checked = false;

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: imgs
          .map((e) =>
          Switch(
              value: _checked,
              inactiveThumbImage: AssetImage(e),
              activeThumbImage: AssetImage('assets/images/pica.gif'),
              onChanged: (v) {
                setState(() => _checked = v);
              }))
          .toList(),
    );
  }
}