**使用到的控件 ChoiceChip .. ** 实现思路:
在一个父类的控件中包裹多个ChoiceChip , 构造 包裹ChoiceChip 时传递构造对象的标识符和选中的回调方法**(选中的回调方法主要是要告诉父控件当前选中ChoiceChip 的标识符)**,这里标识选用的int对象, ChoiceChip 对象选中时,回调父类的方法, 重建整个父对象
class _OriginAuthority extends StatefulWidget {
_OriginAuthority({Key key, @required this.authorityChanged})
: assert(authorityChanged != null),
super(key: key);
@override
__OriginAuthorityState createState() => __OriginAuthorityState();
// 文章的心得发生变化的联动
final ValueChanged<int> authorityChanged;
}
class __OriginAuthorityState extends State<_OriginAuthority> {
// 权限 说明
Map<int, String> _authorities_detail = {
0: '他人可对专栏内容进行转载|复制,但是转载需要标注文章的作者、出处、来源',
1: '非公开发布的心得,仅仅作者可见'
};
// 权限
List<String> _authorities = ['允许规范转载', '个人心得'];
int selected = 0;
ValueChanged<int> onSelectedChanged(int _index) {
widget.authorityChanged(_index);
setState(() {
selected = _index;
});
}
// 迭代器生成list
Iterable<Widget> get _inputSelects sync* {
for (int i = 0; i < _authorities.length; i++) {
yield InputSelect(
index: i,
choice: _authorities[i],
parent: this,
);
}
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: Colors.grey, width: 0.1),
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
//color: Colors.orange,
alignment: Alignment.centerLeft,
child: Text(
"请选择心得权限",
style: TextStyle(
color: Color(0xff182748),
fontSize: 16.0,
),
),
),
Container(
child: Wrap(
// 使用迭代器的方法生成list
children: _inputSelects.toList(),
),
),
Container(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Text(
"©版权摘要说明: ${_authorities_detail[selected] == null ? "" : _authorities_detail[selected]}",
style: TextStyle(
color: Colors.grey[500],
fontSize: 10.0,
fontWeight: FontWeight.normal,
),
),
),
],
),
);
}
}
// 实现 ChoiceInput
// index 为标识ChoiceInput
// parent 为父控件
class InputSelect extends StatelessWidget {
const InputSelect(
{@required this.index,
@required this.widget,
@required this.parent,
@required this.choice})
: super();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ChoiceChip(
label: Text(choice),
//未选定的时候背景
selectedColor: Color(0xff182740),
//被禁用得时候背景
disabledColor: Colors.grey[300],
labelStyle: TextStyle(fontWeight: FontWeight.w200, fontSize: 15.0),
labelPadding: EdgeInsets.only(left: 8.0, right: 8.0),
materialTapTargetSize: MaterialTapTargetSize.padded,
onSelected: (bool value) {
parent.onSelectedChanged(index);
},
selected: parent.selected == index),
);
}
final int index;
final widget;
final parent;
final String choice;
}
复制代码
实现单个选中的效果: