I have searched the web on how to add search functionality to my Flutter application. I have a list view that gets data from a mysql database and pass it as a json string. I want to add a search box on top of the list, when the user enters a string, it will take the string and search the name field of the list and re-populate the list. Here is my code please.
Thank you.
class Home extends StatefulWidget {
Home({Key key}) : super(key: key);
@override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
Future<List<Attendants>> students;
final studentListKey = GlobalKey<HomeState>();
@override
void initState() {
super.initState();
students = getStudentList();
}
Future<List<Attendants>> getStudentList() async {
final response = await http.get("${Env.URL_PREFIX}/list.php");
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Attendants> students = items.map<Attendants>((json) {
return Attendants.fromJson(json);
}).toList();
return students;
}
void refreshStudentList() {
setState(() {
students = getStudentList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: studentListKey,
appBar: AppBar(
title: Text('Members List'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search,
color: Colors.white,),
onPressed: null),
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
refreshStudentList();
},
)
],
),
body: Center(
child: FutureBuilder<List<Attendants>>(
future: students,
builder: (BuildContext context, AsyncSnapshot snapshot) {
// By default, show a loading spinner.
if (!snapshot.hasData) return CircularProgressIndicator();
// Render student lists
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
var data = snapshot.data[index];
return Card(
child: ListTile(
leading: Icon(Icons.person),
trailing: Icon(Icons.view_list),
title: Text(
data.name,
style: TextStyle(fontSize: 20),
),
onTap: () {
Navigator.push(
context,
EnterExitRoute(
exitPage: Home(),
enterPage: Details(attendants: data),
),
);
},
),
);
},
);
},
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return Create();
}));
},
),
);
}
}
Let me know if my question is not clear so I can explain it further