Fluter basic components of the radio buttons and check boxes

Radio buttons and check boxes

Material component library provides Material style switch Switch the radio and check box Checkbox, although they are inherited from StatefulWidget, but they themselves will not save the currently selected state, the selected state are managed by the parent component. When the Switch or Checkbox is clicked, triggers their onChanged callback, we can handle selected to change the logic in this callback.

Common attributes
Radio checkbox

Attributes Explanation
value The value of the radio
onChanged When changing the trigger
activeColor The selected color, background color
groupValue Select the group of values

Code Example:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: "Radio",
    home: MyApp(),
  ));
}


class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> {
  int sex = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Radio")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("大:"),
              Radio(
                value: 1,
                groupValue: this.sex,
                onChanged: (value) {
                  setState(() {
                    this.sex = value;
                  });
                },
              ),
              SizedBox(width: 20),
              Text("小:"),
              Radio(
                value: 2,
                groupValue: this.sex,
                onChanged: (value) {
                  setState(() {
                    this.sex = value;
                  });
                },
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("你选择的是${this.sex == 1 ? "" : ""}")
            ],
          )
        ],
      ),
    );
  }
}

RadioListTile radio button

Attributes Explanation
value true or false
onChanged Time for a change triggered by events
activeColor The selected color, background color
title title
subtitle Subheadings
secondary Configure icon or picture
groupValue Select the group of values

code show as below:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: "RadioListTile",
    home: MyApp(),
  ));
}


class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> {
  int sex = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("我的app")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          RadioListTile(
            value: 1,
            onChanged: (value) {
              setState(() {
                this.sex = value;
              });
            },
            groupValue: this.sex,
            title: Text("一级标题"),
            subtitle: Text("二级标题"),
            secondary: Icon(Icons.camera),
            selected: this.sex == 1,
          ),

        ],
      ),
    );
  }
}

Checkbox checkbox

Attributes Explanation
value Check this box if
onChanged Monitoring, call when the value of the check box should be changed
tristate Default false, if true, the value of the check boxes may be true, false, or null
activeColor When you select this check box to use colors
checkColor Check for color icons When this check box
materialTapTargetSize Configure tap target of minimum size

Code:


Checkbox(
  value: this.valueb, 
  onChanged: (bool value) {
    setState(() {
      this.valueb = value; 
    });
  },

CheckboxListTile box

Attributes Explanation
value Check this box if
onChanged Monitoring, call when the value of the check box should be changed
activeColor When you select this check box to use colors
title A list of the main title
subtitle Subtitle List
isThreeLine Default false
dense This list is whether the tile vertical-intensive part of the list
secondary Displayed in front of the check box widget
selected After the selected text highlighting, default false
controlAffinity Control relative to the position of the text, the default ListTileControlAffinity.platform

Code:


CheckboxListTile(
  secondary: const Icon(Icons.alarm_on),
  title: const Text('每天6:10 响铃'),
  subtitle: Text('12小时58分钟后响铃'),
  value: this.valued, 
  onChanged: (bool value) {
    setState(() {
      this.valued = value; 
    });
  },

下面以一个例子说明状态的维护:
以下代码中,由于需要维护Switch和Checkbox的选中状态,所以SwitchAndCheckBoxTestRoute继承自StatefulWidget 。在其build方法中分别构建了一个Switch和Checkbox,初始状态都为选中状态,当用户点击时,会将状态置反,然后回调用setState()通知Flutter framework重新构建UI

class SwitchAndCheckBoxTestRoute extends StatefulWidget {
  @override
  _SwitchAndCheckBoxTestRouteState createState() => new _SwitchAndCheckBoxTestRouteState();
}

class _SwitchAndCheckBoxTestRouteState extends State<SwitchAndCheckBoxTestRoute> {
  bool _switchSelected=true; //维护单选开关状态
  bool _checkboxSelected=true;//维护复选框状态
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Switch(
          value: _switchSelected,//当前状态
          onChanged:(value){
            //重新构建页面  
            setState(() {
              _switchSelected=value;
            });
          },
        ),
        Checkbox(
          value: _checkboxSelected,
          activeColor: Colors.red, //选中时的颜色
          onChanged:(value){
            setState(() {
              _checkboxSelected=value;
            });
          } ,
        )
      ],
    );
  }
}

总结
通过Switch和Checkbox我们可以看到,虽然它们本身是与状态(是否选中)关联的,但它们却不是自己来维护状态,而是需要父组件来管理状态,然后当用户点击时,再通过事件通知给父组件,这样是合理的,因为Switch和Checkbox是否选中本就和用户数据关联,而这些用户数据也不可能是它们的私有状态。我们在自定义组件时也应该思考一下哪种状态的管理方式最为合理。

发布了13 篇原创文章 · 获赞 38 · 访问量 2553

Guess you like

Origin blog.csdn.net/m0_46369686/article/details/104648877