在颤动的列表视图中搜索
Posted
技术标签:
【中文标题】在颤动的列表视图中搜索【英文标题】:searching in listview in flutter 【发布时间】:2020-05-03 06:33:03 【问题描述】:我正在尝试在 listview 中搜索,但我在搜索框中的字符串没有反映在 listview 中。我在打印时在控制台中获取字符串但 listview 没有反映。这是我编写的代码。我有获取一个嵌套的 json 数组并将其显示在一个列表视图中,并希望对其执行搜索功能。我是新来的,所以不知道如何做到这一点。
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: orange,
title: Text('ATTENDENCE'),
),body:
Stack(
children: <Widget>[
Container(
color: Colors.white,
),
Container(
color: skyblue,
width: double.infinity,
height: 65,
padding: EdgeInsets.only(right: 20,left: 20,top: 10,bottom: 10),
child:Row(
children: <Widget>[
Container(
child:Column(children: <Widget>[
Text("Center Name",style: TextStyle(color: lightGrey,fontSize: 17)),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.centernametext.toUpperCase(),style: TextStyle(color:
Colors.black,fontSize: 13)),
),
],)
),
Spacer(),
Container(
child:Column(children: <Widget>[
Text("Batch",style: TextStyle(color: lightGrey,fontSize: 17),textAlign:
TextAlign.left,),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.batchname,style: TextStyle(color: Colors.black,fontSize: 13)),),
],)
),
Spacer(),
Container(
child:Column(children: <Widget>[
Text("Date",style: TextStyle(color: lightGrey,fontSize: 17)),
Container(
margin: EdgeInsets.only(top:5),
child:Text(widget.date,style: TextStyle(color: Colors.black,fontSize: 13)),
),
],)
),
],
)
),
_searchBar(),
Container(
color: skyblue,
width: double.infinity,
height: 50,
margin: EdgeInsets.only(top:170),
padding: EdgeInsets.only(right: 20,left: 20,top: 10,bottom: 10),
child:Row(
children: <Widget>[
Container(
child: Checkbox(
value: checkVal,
onChanged: (bool value)
setState(()
checkVal = value;
if(checkVal==true)
isSelected=true;
else
isSelected=false;
);
),
),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Name",style: TextStyle(color: lightGrey,fontSize: 17)),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Age",style: TextStyle(color: lightGrey,fontSize: 17),textAlign:
TextAlign.left,),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Level no.",style: TextStyle(color: lightGrey,fontSize: 17)),
],)
),
Spacer(),
Container(margin: EdgeInsets.only(top:5),
child:Column(children: <Widget>[
Text("Attend",style: TextStyle(color: lightGrey,fontSize: 17)),
],)
),
],
)
),
Container(
margin: EdgeInsets.only(top:230),
child: ListView.builder(
//addAutomaticKeepAlives: true,
itemCount: filteredlist==null?0:filteredlist.length,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, index)
return new CustomWidget(
selected:isSelected,
rest:filteredlist,
index: index,
longPressEnabled: longPressFlag,
callback: ()
if (indexList.contains(index))
indexList.remove(index);
else
indexList.add(index);
longPress();
,
);
)
)])));
_searchBar()
return Container(
child:Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 250,
height: 40,
margin: EdgeInsets.only(left:20,top:90),
child:TextField(
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
prefixIcon: new Padding(
padding: const EdgeInsets.only( top: 13, left: 0, right: 5, bottom: 13),
child: new SizedBox(
height: 2,
child: Image.asset('assets/search.png'),
),
),
labelText: "Search by name",
labelStyle: TextStyle(
color: lightGrey,
fontSize: 15
),
border: OutlineInputBorder( borderSide: BorderSide(color: lightGrey, width: 0.5),
borderRadius: BorderRadius.circular(10.0)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: orange, width: 0.5),
borderRadius: BorderRadius.circular(10.0)
)),
controller: controller,
onChanged: (string)setState(()
//print("log");
for (i = 0; i < rest.length; i++)
if(rest[i]['student']['name'].contains(string))
print(string);
print(i);
filteredlist.add(filteredlist[i]['student']['name']);
print(filteredlist);
filteredlist = rest
.where((u) => (
(u[i]['student']['name']).toString().toLowerCase().contains(string.toLowerCase())
)).toList();
);
,
)
),
Container(
margin: EdgeInsets.only(left: 10,top: 85),
child: MaterialButton(
shape: RoundedRectangleBorder(side: BorderSide(color:
blue),borderRadius:BorderRadius.circular(10.0)),
minWidth: 100,
height: 40,
// set minWidth to maxFinite
color: blue,
textColor: Colors.white,
onPressed: ()
,
child: Text("Search",style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.w500,
color: Colors.white
),),
)
)
],
)
);
Future<List<Autogenerated>> StudentListRequest() async
String as=widget.accesstoken.toString();
var url = 'http://demo.neurapses.com:3032/students?
center=5ca5ba30e0adb9c1839aa0d2&batch=5ca5c81597f8a03368df072c';
var response = await http.get(url,
headers:
'Content-Type': 'application/json',
'Authorization': 'Bearer $as'
,
);
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null)
throw new Exception("Error while fetching data");
else
setState(()
var data = json.decode(response.body);
rest = data['docs'];
for(var rest in rest)
list.add(Autogenerated.fromJson(rest));
filteredlist=rest;
);
return list;
getStringValuesSF() async
SharedPreferences prefs = await SharedPreferences.getInstance();
str_accesstoken = prefs.getString('accesstoken');
class Autogenerated
List<Docs> docs;
Autogenerated(
this.docs,
);
Autogenerated.fromJson(Map<String, dynamic> json)
if (json['docs'] != null)
docs = new List<Docs>();
json['docs'].forEach((v)
docs.add(new Docs.fromJson(v));
);
Map<String, dynamic> toJson()
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.docs != null)
data['docs'] = this.docs.map((v) => v.toJson()).toList();
return data;
class Docs
Student student;
Docs(
this.student,
);
Docs.fromJson(Map<String, dynamic> json)
student =
json['student'] != null ? new Student.fromJson(json['student']) : null;
Map<String, dynamic> toJson()
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.student != null)
data['student'] = this.student.toJson();
return data;
class Student
String name;
Student(
this.name,
);
Student.fromJson(Map<String, dynamic> json)
name = json['name'];
Map<String, dynamic> toJson()
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
return data;
class CustomWidget extends StatefulWidget
final int index;
final bool longPressEnabled;
final VoidCallback callback;
final List rest;
bool selected;
CustomWidget(Key key, this.selected, this.rest, this.index, this.longPressEnabled, this.callback) :
super(key: key);
@override
_CustomWidgetState createState() => new _CustomWidgetState();
class _CustomWidgetState extends State<CustomWidget>
final skyblue=Color(0xffF1F5F9);
@override
Widget build(BuildContext context)
return new Card(
margin: new EdgeInsets.all(5.0),
color: widget.selected ? Colors.grey[300]:Colors.white,
child: CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
onChanged: (val)
setState(()
widget.selected = !widget.selected;
);
,
value: widget.selected,
title:
Container(
// color: mycolor,
child: Row(
children: <Widget>[
Container(
child: Text(widget.rest[widget.index]['student']['name'], style: TextStyle(color: Colors
.black, fontSize: 15),)
),
Spacer(),
Container(
child: Text("", style: TextStyle(color: Colors
.black, fontSize: 15),)
),
Spacer(),
Container(
child: Text(
"", style: TextStyle(color: Colors.black,
fontSize: 15),)
),
Spacer(),
Container(
child: Text("", style: TextStyle(color: Colors
.black, fontSize: 15),)
),
],
),
),
));
【问题讨论】:
【参考方案1】:假设你的休息列表有数据,
onChanged: (stringToSearch)
filteredList = rest.where((f)
var dataName = f['student']['name'].toString().toLowerCase();
return dataName.contains(textToSearch);
);
无需循环
【讨论】:
它正在工作,但现在我正在列表视图中搜索文本并在列表视图中选择该文本行,当我清除搜索文本字段时,该选定行将被取消选择。【参考方案2】:将侦听器添加到您的搜索 TextField 控制器并相应地生成新的过滤列表列表,然后使用
setState(()
currentList = newFilteredList;
);
设置新的过滤列表并重新构建整个小部件。
【讨论】:
以上是关于在颤动的列表视图中搜索的主要内容,如果未能解决你的问题,请参考以下文章