I am searching in ListView and I am getting search result in flitered list but when I am selecting the searched item in listview and clear the searchbox in the original list my selected item is deselected. My original list is "rest" list in the code and filtered list is "filteredList used in code. Help me to solve my issue as I am new to flutter.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

String stringValue="default";
String Currentdate;
const lightGrey = Color(0xff858585);
const darkGrey = Color(0xff404042);
const orange = Color(0xffff8500);
const blue = Color(0xff2f5597);
const skyblue=Color(0xffF1F5F9);
const darkblue=Color(0xffD4E7F9);

class AttendencePage2 extends StatefulWidget {
  final String centernametext,batchname,date,centerid,batchid,accesstoken;
  AttendencePage2(this.centernametext,this.batchname,this.date,this.centerid,this.batchid,this.accesstoken);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AttendencePage2();
  }

}

class _AttendencePage2 extends State<AttendencePage2> {
  int i;
  String str_accesstoken;
  List rest;
  List<Autogenerated> list=  List<Autogenerated>();
  List filteredlist;
  TextEditingController controller = new TextEditingController();
  bool isSelected = false;
  List<int> indexList = new List();
  bool longPressFlag = false;

  void longPress() {
    setState(() {
      if (indexList.isEmpty) {
        longPressFlag = false;
      } else {
        longPressFlag = true;
      }
    });
  }
  var mycolor=Colors.white;
  bool checkVal = false;
  bool checkVal2=false;
  @override
  void initState() {
    super.initState();
    getStringValuesSF();
    StudentListRequest();
     }
  @override
  Widget build(BuildContext context) {
//    for (var i = 0; i < 50; i++) {
//      indexList.add(Element(isSelected: false));
//    }
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.white, // navigation bar color
      statusBarColor: Colors.black, // status bar color
    ));

    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)),
                ),

              ],)
              //child:

            ),
              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)),
                    ),

                  ],)

              ),
              Container(
                margin: EdgeInsets.only(left: 10),
                child: Image.asset('assets/grey_edit.png',width: 20,height: 25),
              ),
            ],
          )
        ),
     _searchBar(),
          Container(
              color: skyblue,
              width: double.infinity,
              height: 50,
              margin: EdgeInsets.only(top:155,left: 10,right: 10),
              padding: EdgeInsets.only(right: 20,left: 0,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: 15)),
                      ],)

                  ),
                  Spacer(),
                  Container(margin: EdgeInsets.only(top:5),
                      child:Column(children: <Widget>[
                        Text("       ",style: TextStyle(color: lightGrey,fontSize: 15),textAlign: TextAlign.left,),

                      ],)

                  ),
                  Spacer(),
                  Container(margin: EdgeInsets.only(top:5),
                      child:Column(children: <Widget>[
                        Text("Level ",style: TextStyle(color: lightGrey,fontSize: 15)),

                      ],)

                  ),
                  Spacer(),
                  Container(margin: EdgeInsets.only(top:5),
                      child:Column(children: <Widget>[
                        Text("No. of class",style: TextStyle(color: lightGrey,fontSize: 15)),

                      ],)

                  ),
                  Spacer(),
                  Container(margin: EdgeInsets.only(top:5),
                      child:Column(children: <Widget>[
                        Text("Attend",style: TextStyle(color: lightGrey,fontSize: 15)),

                      ],)

                  ),
                ],
              )
          ),
          Container(
              margin: EdgeInsets.only(top:205,left: 10,right: 10),
              decoration: BoxDecoration(
                  border: Border.all(color: darkblue)
              ),
              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: () {

                      longPress();
                    },
                  );

                  })

      )])));

  }

  _searchBar() {

    return Container(
        child:Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[

            Container(
                width: 350,
                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(5.0)),
                      focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: orange, width: 0.5),
                          borderRadius: BorderRadius.circular(5.0)
                      )),
                  controller: controller,
                  onChanged: (string){setState(() {
                     filteredlist=rest.where((f){
                       var dataName=f['student']['name'].toString().toLowerCase();
                       var dataName2=f['course']['level_no'].toString().toLowerCase();
                       return dataName.contains(string)||dataName2.contains(string);
                     }).toList();
                    }
                    );
                  },
                )
            ),
          ],
        )
    );
  }

  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 GestureDetector(
        onLongPress: () {
      widget.callback();
    },
    onTap: () {
    if (widget.longPressEnabled) {
    widget.callback();
    }
    },
    child:Container(
        margin: new EdgeInsets.only(top:5.0),
        color: widget.selected ? Colors.grey[300]:Colors.white,
        child:Row(children: <Widget>[
          Flexible(
              fit:FlexFit.loose,
              child: ListTile(
              contentPadding: EdgeInsets.only(left: 0.0, right: 0.0),
                title:
                Container(
                  child:Column(children: <Widget>[

                 Row(
                    children: <Widget>[
                      Container(
                        child: Checkbox(
                          onChanged: (val) {
                            setState(() {
                              widget.selected = !widget.selected;
                            });
                          },
                          value: widget.selected,
                        ),
                      ),
                      Container(

                          child:Container(width:80,child:Text(widget.rest[widget.index]['student']['name'], style: TextStyle(color: Colors
                              .black, fontSize: 13),
                          )),

                      ),
                      Spacer(),
                      Container(

                          child: Text(widget.rest[widget.index]['course']['level_no'], style: TextStyle(color: Colors
                              .black, fontSize: 13),)
                      ),
                      Spacer(),
                      Container(

                          child: Text(
                            "", style: TextStyle(color: Colors.black,
                              fontSize: 13),)
                      ),
                      Spacer(),
                      Container(
                          child: Text("", style: TextStyle(color: Colors
                              .black, fontSize: 13),)
                      ),
                    ],
                  ),
                    Container(
                        color: darkblue,
                        height: 0.7,
                        width: double.infinity,

                    ),

                    ]),
                // onLongPress: toggleSelection,
              ))
          )],),
        ));
      }
}


Solution 1: Kalpesh Rupani

Add Search Bar

TextField(
  controller: editingController,
  decoration: InputDecoration(
      labelText: "Search",
      hintText: "Search",
      prefixIcon: Icon(Icons.search),
      border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),

Code for UI showing a search bar and ListView with 1000 items

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'ListView with Search'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController editingController = TextEditingController();

  final duplicateItems = List<String>.generate(10000, (i) => "Item $i");
  var items = List<String>();

  @override
  void initState() {
    items.addAll(duplicateItems);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (value) {

                },
                controller: editingController,
                decoration: InputDecoration(
                    labelText: "Search",
                    hintText: "Search",
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(25.0)))),
              ),
            ),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: items.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${items[index]}'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}