这是我的学生列表界面,里面有一个添加学生的按钮,在表单上点保存后就会弹回学生列表。
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();
},
),
// =======================================================
),
// ================== ADD STUDENT BUTTON =======================
Widget _buidFloatingButton() {
return FloatingActionButton(
child:Icon(Icons.person_add),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) {
_getStudents();
});
},
);
}
// =======================================================
}
}
我试图在表单弹出后用这段代码刷新学生列表,如上图所示。
Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) => () {
_getStudents();
});
它没有刷新学生列表,但如果我点击刷新按钮,它就会刷新,这两个尝试都是在执行同一个_getStudentes()函数。
在保存按钮的最后,我只是做了一个。
Navigator.pop(context);
我漏了什么?
谢谢。
你是 返回函数 与 (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();
}