场景 : 从数据库获取到数据 需要将数据加载到页面上,而且还可以进行多选,并保存数据。
实现效果:
详细代码:
import 'dart:core';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class UserInfo{
String Name;
int Id;
bool isSelected;
UserInfo({this.Name,this.Id,this.isSelected=false});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'CheckBoxListTitle组件',
home: new Scaffold(
appBar: new AppBar(
title: new Text('CheckBoxListTitle组件'),
),
body:SingleChildScrollView(
child: DemoPage(),
),
),
);
}
}
class DemoPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => DemoPageState();
}
class DemoPageState extends State<DemoPage> {
List<UserInfo> userMapList=new List();
List<String> selName=new List();
List<String> selIds=new List();
@override
void initState() {
// TODO: implement initState
addUser();
}
addUser(){
for(int i=0;i<=8;i++){
UserInfo u =new UserInfo();
u.Name="A$i";
u.Id=i;
userMapList.add(u);
}
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Column(
children: userMapList.map((f){
return Column(
children: <Widget>[
Container(
child: CheckboxListTile(
value: f.isSelected,
onChanged: (bool){
setState(() {
f.isSelected=!f.isSelected;
//保存已选中的
if(f.isSelected){
if(!selName.contains(f.Name))
selName.add(f.Name);
if(!selIds.contains(f.Id.toString()))
selIds.add(f.Id.toString());
}//删除
else{
if(selName!=null && selName.contains(f.Name))
selName.remove(f.Name);
if(selIds!=null && selIds.contains(f.Id.toString()))
selIds.remove(f.Id.toString());
}
});
},
title: Text(f.Name),
controlAffinity: ListTileControlAffinity.platform,
activeColor: Colors.green,
),
),
],
);
}).toList()// <Widget>[
//],
),
Container(
color: Colors.grey[100],
height: 20,
),
Column(
children: <Widget>[
Container(height: 30,
child: Text("选中Name:"+selName.join(","),style: TextStyle(color:Colors.red),),
),
Container(
height: 30,
child: Text("选中Id:"+selIds.join(","),style: TextStyle(color:Colors.green)),
)
],
),
],
);
}
}
有问题可留言!