android - Flutter:是否可以从其他脚本中的状态运行函数
问题描述
所以我的问题是:是否可以在其他脚本中从状态运行函数?
例如:我有 2 个脚本,假设我有 main.dart 和 loadingScreen.dart
主要.dart
//...
OutlineButton(
child: Text("Status", style: TextStyle(color: Colors.white, fontSize: 17), textAlign: TextAlign.center,),
borderSide: BorderSide(color: Colors.grey[400]),
onPressed: () async {
Navigator.pushNamed(context, '/loadingScreen', arguments: {"text": "Checking\nstatus"});
//...
// <--- Here I want to run updateLoadingText from loadingScreen.dart
Navigator.pop(context);
}
),
//...
加载屏幕.dart
class _LoadingScreenState extends State<LoadingScreen> {
Map data = {};
String loadingText;
updateLoadingText(newText){
//...
}
@override
Widget build(BuildContext context) {
//...
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
backgroundColor: Colors.grey[800],
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SpinKitCubeGrid(
color: Colors.white,
size: 80,
),
SizedBox(height: 24,),
Text(
loadingText,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 35,
),
)
],
),
)
),
);
}
}
是否可以在 main.dart 中运行 updateLoadingText?
谢谢帮助!
解决方案
您可以通过将密钥传递给小部件然后使用该密钥访问小部件的状态来做到这一点。(您需要公开状态类才能执行此操作。)
主要.dart
// In the class fields
final loadingScreenKey = GlobalKey<LoadingScreenState>();
// Where you build LoadingScreen
LoadingScreen(
key: loadingScreenKey,
// ...
),
// Button code
OutlineButton(
// ...
onPressed: () async {
// ...
loadingScreenKey.currentState.updateLoadingText(...),
},
),
免责声明
像这样直接从另一个小部件调用状态方法通常被认为是不好的形式,因为这会产生高度耦合和分散的意大利面条代码。因此,您应该查看一个系统,您可以通过公正的服务通知小部件进行更改。有很多方法可以做到这一点,例如使用事件总线、aChangeNotifier
或使用诸如 provider 或 flutter_bloc 之类的状态管理库。
推荐阅读
- windows - 替换嵌入图标图像中的 PE,无需重新对文件重新签名
- reflection - 在生成的函数中究竟如何定义“与 Core.Compiler 交互”?
- android - Android Studio APK Analyzer 不显示详细信息结果
- azcopy - Azcopy 生成的 JSON 文件是什么意思
- python - 在 Pandas Column 中搜索 Pattern,抽象 Pattern 左侧的值
- javascript - 是的,使用正则表达式和不区分大小写的验证
- cmake - CMake 库文件丢失
- asp.net-core - 如何在 Razor 中将初始过滤器添加到 BootstrapGridView
- java - 注册多个 ClientHttpRequestInterceptor 时 RestTemplate 的行为是什么?
- angular - Visual Studio Code v1.37 没有下划线错误