这是我的学生列表屏幕,它带有一个添加学生按钮,在点击表单上的保存后,它会跳回到学生列表。
class _StudentListState extends State<StudentList> {
var students = new List<Student>();
_getStudents() {
APIServices.fetchStudents().then((response) {
setState(() {
Iterable list = json.decode(response);
students = list.map((model) => Student.fromJson(model)).toList();
});
});
}
@override
void initState() {
super.initState();
_getStudents();
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton:_buidFloatingButton(),
appBar: _buildAppBar(context),
bottomNavigationBar: BottomAppBar(
// ================== REFRESH BUTTON ============================
child: FlatButton(
child:Icon(Icons.refresh),
onPressed: () {
_getStudents();
},
),
// =======================================================
),
...
}
}
我正在尝试使用此代码在表单弹出后刷新学生列表,如以上代码所示:
Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) => () {
_getStudents();
});
不会刷新学生列表,但是如果我点击刷新按钮,它将刷新,两次尝试都执行相同的_getStudentes()函数。
我想念什么?
谢谢。
您正在用(value) => () { ... }
返回功能。
JavaScript和Dart的速记语法在这方面有所不同,让我解释一下:
// Expression that returns a function.
() {
...
}
// You could also assign it to a variable:
final foo = () { return 3; };
// Now, you can call foo:
final bar = foo();
因此,您正在使用(value) => () { ... }
返回函数。
您想要做的是以下任一项:
(value) => _getStudents()
// or
(value) {
_getStudents();
}