Flutter Switch


简介

Switch 是一个切换按钮组件,通常用于设置的选项里。

基本用法

通常用于Bool值参数的设置.

高级用法

当默认的样式无法满足需求时, 我们可以通过自定义各部件样式.

  • activeColor[Color] 当按钮状态通激活态时, 按钮的背景颜色
  • activeThumbImage [ImageProvider] 当按钮状态处于激活态时, 按钮的背景图像
  • activeTrackColor [Color] 当按钮状态处于激活态时, 滑轨的颜色
  • inactiveThumbColor [Color] 当按钮处于非激活状态时, 按钮的背景颜色, 与activeColor正好状态相反
  • inactiveThumbImage [ImageProvider] 当按钮状态处于非激活态时, 按钮的背景图像
  • inactiveTrackColor [Color] 当按钮状态处于非激活态时, 滑轨的颜色

实例演示

import 'package:flutter/material.dart';



class SwitchDemo extends StatefulWidget {
  _Demo createState() => _Demo();
}

class _Demo extends State<SwitchDemo> {
  bool check = false;
  Widget build(BuildContext context) {
    return  Switch(
      value: this.check,
      onChanged: (bool val) {
        this.setState(() {
          this.check = !this.check;
        });
      },
    );
  }
}

class SwitchHighDemo extends StatefulWidget {
  _SwitchHighDemo createState() => _SwitchHighDemo();
}

class _SwitchHighDemo extends State<SwitchHighDemo> {
  bool check = false;
  Widget build(BuildContext context) {
    return  Switch.adaptive(
      value: this.check,
      activeColor: Colors.blue,     // 激活时原点颜色
      onChanged: (bool val) {
        this.setState(() {
          this.check = !this.check;
        });
      },
    );
  }
}


class SwitchTypesDemo extends StatefulWidget {
  _SwitchTypesDemo createState() => _SwitchTypesDemo();
}

class _SwitchTypesDemo extends State<SwitchTypesDemo> {
  bool check = false;
  Widget build(BuildContext context) {
    return  Switch(
      value: this.check,
      activeTrackColor:Colors.green,
      inactiveThumbColor: Colors.black,
      inactiveThumbImage: NetworkImage('https://flutter.io/images/homepage/header-illustration.png'),
      activeThumbImage: NetworkImage(
          "https://flutter.io/images/homepage/screenshot-2.png"
      ),
      inactiveTrackColor: Colors.yellow,
      activeColor: Colors.blue,     // 激活时原点颜色
      onChanged: (bool val) {
        this.setState(() {
          this.check = !this.check;
        });
      },
    );
  }
}