我正在开发一个小部件,它包含未来约会的列表视图。但我需要的信息是通过异步函数获取的。该函数每秒加载几个项目,但需要一段时间才能完成。为了加快时间,我在应用程序启动时就获取了信息。
主要方法
Future main() async {
void initAppointmentList() async {
await AppointmentList().init(30);
}
initAppointmentList();
}
获取预约列表
class AppointmentList {
List<Map<String, String>> appointments = [];
Future init(int range) async {
for (int i = 0; i < range; i++) {
/*
HTTP GET Code fetching data
*/
appointments.add(/* The Data */);
}
day = day.add(const Duration(days:1));
}
}
}
Flutter 小部件
class AppointmentOverviewContainer extends StatefulWidget {
const AppointmentOverviewContainer({super.key});
@override
State<AppointmentOverviewContainer> createState() => _AppointmentOverviewContainerState();
}
class _AppointmentOverviewContainerState extends State<AppointmentOverviewContainer> {
List<Map<String, String>> appointments = AppointmentList().appointments;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return (/* If Appointment List Has At Least One Item Loaded */) ?
FittedBox (
fit: BoxFit.scaleDown,
child: Text(appointments[0]['Name'] ?? '',
style: GoogleFonts.lato(fontSize: 20, fontWeight: FontWeight.w500)),
) :
FittedBox (
fit: BoxFit.scaleDown,
child: Text('Loading Appointments',
style: GoogleFonts.lato(fontSize: 20, fontWeight: FontWeight.w500)),
),
);
}
}
Flutter 小部件是否可以检查约会列表是否已更新?如果有,则显示最新的。但是,我也想要它,以便它能够检查提取何时完全完成。
由于异步函数是在main方法中初始化的,所以我无法使用FutureBuilder
我无法使用setState,因为变量更新是在小部件外部完成的
将获取内容放入小部件内部会阻止我从一开始就运行它
您可以使 AppointmentList 扩展 ChangeNotifier 并在小部件中订阅它。然后,您可以在每次获取约会时触发 setState。
class AppointmentList extends ChangeNotifier {
List<Map<String, String>> appointments = [];
Future init(int range) async {
for (int i = 0; i < range; i++) {
/*
HTTP GET Code fetching data
*/
appointments.add(/* The Data */);
notifyListeners();
}
day = day.add(const Duration(days:1));
}
}
}
并且处于小部件状态
class _AppointmentOverviewContainerState extends State<AppointmentOverviewContainer> {
final appointmentList = AppointmentList();
@override
void initState() {
super.initState();
appointmentList.addListener(_onAppointmentAdded);
}
@override
Widget build(BuildContext context) {
return (/* If Appointment List Has At Least One Item Loaded */) ?
FittedBox (
fit: BoxFit.scaleDown,
child: Text(appointmentList.appointments.first['Name'] ?? '',
style: GoogleFonts.lato(fontSize: 20, fontWeight: FontWeight.w500)),
) :
FittedBox (
fit: BoxFit.scaleDown,
child: Text('Loading Appointments',
style: GoogleFonts.lato(fontSize: 20, fontWeight: FontWeight.w500)),
),
);
}
@override
void dispose(){
appointmentList.removeListener(_onAppointmentAdded);
}
void _onAppointmentAdded(){
setState((){
//Do your logic
});
}
但是要使其工作,您应该在小部件中初始化约会列表,因为在主部件和小部件中不会有相同的实例。除非你有一些依赖注入。
我同意Randal Schwartz的评论。通过从 main 获取数据而不是从小部件的 initState 中获取数据,您不会获得可见的性能。