avatar

目录
Flutter中实现圆形边框的CheckBox

Flutter中实现圆形边框的CheckBox

其实有两种思路

1.通过组合组件实现

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import 'package:flutter/material.dart';

class RoundCheckBox extends StatefulWidget {
final bool value;

final ValueChanged<bool> onChanged;

RoundCheckBox({Key key, @required this.value, this.onChanged})
: super(key: key);

@override
_RoundCheckBox1State createState() => _RoundCheckBoxState();
}

class _RoundCheckBoxState extends State<RoundCheckBox1> {
bool _value;
ValueChanged<bool> _onChanged;

@override
void initState() {
super.initState();
_value = widget.value;
_onChanged = widget.onChanged;
}

/// value: _throwShotAway,
/// onChanged: (bool newValue) {
/// setState(() {
/// _throwShotAway = newValue;
/// });
/// },

@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
onTap: () {
_value = !_value;
_onChanged(_value);
},
child: Padding(
padding: const EdgeInsets.all(2),
child: _value
? Icon(
Icons.check_circle,
size: 18.0,
color: Colors.blue,
)
: Icon(
Icons.panorama_fish_eye,
size: 18.0,
color: Colors.grey,
),
)),
);
}
}

2 参考CheckBox,将绘制方形代码部分改成圆角

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 CheckBox.class
/// The width of a checkbox widget.checkBox的宽度
static const double width = 18.0;
///边框的Size
const double _kEdgeSize = Checkbox.width;
///边框的圆角
const Radius _kEdgeRadius = Radius.circular(1.0);
///绘制外边框
RRect _outerRectAt(Offset origin, double t) {
final double inset = 1.0 - (t - 0.5).abs() * 2.0;
final double size = _kEdgeSize - inset * _kStrokeWidth;
final Rect rect = Rect.fromLTWH(origin.dx + inset, origin.dy + inset, size, size);
return RRect.fromRectAndRadius(rect, _kEdgeRadius);
}

可以看到方形边框的绘制是通过_outerRectAt()方法实现的,那么把圆角增大,是不是可以达到圆形边框的效果.

所以我把CheckBox的源码拷贝下来了,把圆角改成了宽度的一半,即可实现圆形边框的CheckBox.修改的代码如下

Code
1
2
3
4
///修改前
const Radius _kEdgeRadius = Radius.circular(1.0);
///修改后
const Radius _kEdgeRadius = Radius.circular(9.0);
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论