Flutter使用state实现列表单选效果

Flutter使用state实现单选效果

1
2
3
4
setState(() {
sampleData.forEach((element) => element.isSelected = false);
sampleData[index].isSelected = true;
});
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import 'package:flutter/material.dart';

class StateRadioBoxDemoPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _StateRadioBoxDemoPageState();
}

class _StateRadioBoxDemoPageState extends State<StateRadioBoxDemoPage> {
List<RadioModel> sampleData = new List<RadioModel>();

@override
void initState() {
super.initState();
sampleData.add(new RadioModel(false, 'A', 'www.appblog.cn'));
sampleData.add(new RadioModel(false, 'G', 'www.google.com'));
sampleData.add(new RadioModel(false, 'B', 'www.baidu.com'));
sampleData.add(new RadioModel(false, 'G', 'www.github.com'));
}

Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("ListItem"),
),
body: new ListView.builder(
itemCount: sampleData.length,
itemBuilder: (BuildContext context, int index) {
return new InkWell(
//highlightColor: Colors.red,
splashColor: Colors.blueAccent,
onTap: () {
setState(() {
sampleData.forEach((element) => element.isSelected = false);
sampleData[index].isSelected = true;
});
},
child: new RadioItem(sampleData[index]),
);
},
),
);
}
}

class RadioItem extends StatelessWidget {
final RadioModel _item;
RadioItem(this._item);

@override
Widget build(BuildContext context) {
return new Container(
margin: new EdgeInsets.all(15.0),
child: new Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Container(
height: 50.0,
width: 50.0,
child: new Center(
child: new Text(_item.buttonText,
style: new TextStyle(
color:
_item.isSelected ? Colors.white : Colors.black,
//fontWeight: FontWeight.bold,
fontSize: 18.0)),
),
decoration: new BoxDecoration(
color: _item.isSelected
? Colors.blueAccent
: Colors.transparent,
border: new Border.all(
width: 1.0,
color: _item.isSelected
? Colors.blueAccent
: Colors.grey),
borderRadius: const BorderRadius.all(const Radius.circular(2.0)),
),
),
new Container(
margin: new EdgeInsets.only(left: 10.0),
child: new Text(_item.text),
)
],
),
);
}
}

class RadioModel {
bool isSelected;
final String buttonText;
final String text;

RadioModel(this.isSelected, this.buttonText, this.text);
}

Flutter_StateCheckBox

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :