flutter - 在 Flutter 中从 main() 调用 setState()
问题描述
在我调用 main() 的每个 Cron-Job 之后,如何调用特定 State-Class 的 setState() 方法?
主要的():
void main() async {
new Cron().schedule(new Schedule.parse('* * * * *'), () async {
uploadDocuments();
});
runApp(MaterialApp(
home: MainMenu(),
));
}
类,我希望在其中调用 setState():
class DbObjectsDetails extends StatefulWidget
@override
_DbObjectsDetailsState createState() => _DbObjectsDetailsState();
}
class _DbObjectsDetailsState extends State<DbObjectsDetails> {
void initState() {
loadFilesFromDatabase(true);
}
}
解决方案
您可以尝试使用get_it
包注册一个单例,GlobalKey
然后在两个地方都使用它
此代码可能有效:
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
GetIt locator = GetIt.instance..allowReassignment = true;
void setupLocator() {
locator.registerLazySingleton(() => GlobalKey<DbObjectsDetailsState>());
}
GlobalKey<DbObjectsDetailsState> newWidgetKey() {
locator.registerSingleton(GlobalKey<DbObjectsDetailsState>());
return locator<GlobalKey<DbObjectsDetailsState>>();
}
void main() async {
setupLocator()
new Cron().schedule(new Schedule.parse('* * * * *'), () async {
//you can acces the current state of the widget like that:
locator<GlobalKey<DbObjectsDetailsState>>().currentState?.rebuild();});
runApp(MaterialApp(
home: DbObjectsDetails(key: newWidgetKey()),
));
}
class DbObjectsDetails extends StatefulWidget {
DbObjectsDetails({Key key}) : super(key: key);
@override
DbObjectsDetailsState createState() => DbObjectsDetailsState();
}
class DbObjectsDetailsState extends State<DbObjectsDetails> {
@override
Widget build(BuildContext context) {
throw UnimplementedError();
}
void rebuild() => setState((){})
}
推荐阅读
- postgresql - 如何在覆盖“CREATE UNIQUE INDEX”约束时批量更新?
- node.js - 有没有办法使用类验证器实现文件上传验证?
- android - Android Grid Layout Cardview 项目仅在屏幕顶部可见
- jquery - 具有服务器端处理的 Datatable 的 Codeigniter 动态列
- html - 如何使用 CSS 在导航栏下添加阴影?
- javascript - 显示一个 div 并隐藏其余的 onclick
- java - 在服务中的每个方法调用之前运行注释处理器
- android - Android 如何实现 AsyncTask?EditText 没有响应的地方
- html - 使用时提交什么数据
- groovy - 加载 groovy 文件时捕获异常