Last active
March 14, 2020 02:07
-
-
Save JaveedIshaq/092560b93217dec512c00994b41e09b6 to your computer and use it in GitHub Desktop.
Search from a list view in flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.green, | |
), | |
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(); | |
} | |
void filterSearchResults(String query) { | |
List<String> dummySearchList = List<String>(); | |
dummySearchList.addAll(duplicateItems); | |
if(query.isNotEmpty) { | |
List<String> dummyListData = List<String>(); | |
dummySearchList.forEach((item) { | |
if(item.contains(query)) { | |
dummyListData.add(item); | |
} | |
}); | |
setState(() { | |
items.clear(); | |
items.addAll(dummyListData); | |
}); | |
return; | |
} else { | |
setState(() { | |
items.clear(); | |
items.addAll(duplicateItems); | |
}); | |
} | |
} | |
@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) { | |
filterSearchResults(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]}'), | |
); | |
}, | |
), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment