【发布时间】:2021-02-13 09:05:09
【问题描述】:
我在网上搜索了如何向我的 Flutter 应用程序添加搜索功能。我有一个列表视图,它从 mysql 数据库中获取数据并将其作为 json 字符串传递。我想在列表顶部添加一个搜索框,当用户输入一个字符串时,它将获取该字符串并搜索列表的名称字段并重新填充列表。这是我的代码。
谢谢。
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();
}));
},
),
);
}
}
如果我的问题不清楚,请告诉我,以便我进一步解释
【问题讨论】: