interface - 如何从界面设置状态?
问题描述
我有一个实现接口的类
class _UserSignupInterface implements UserSignupInterface {
@override
void onSuccess() {
}
@override
void onError(String message) {
}
}
但是,我无法通过 setState() 更改变量,我将使用它来更改页面上显示的文本。
我试图将接口扩展到我的接口_SignupSelectUsernamePageState
并在接口内调用更改状态,但这只会导致错误,也许 setState() 不应在接口内调用。
我也尝试将变量放在StatefulWidget
和之外PageState
。但是,如果我不能在界面内使用 setState() ,那么简单地更新它的值就没有任何意义,因为它不会反映更改页面上的文本。
该接口是我用来处理从网络请求接收到的响应数据的回调。
在and (扩展 StatefulWidget)Text
之外更改 Widget 文本的正确方法是什么?因为我必须处理界面内的数据处理和变量更新。StatefulWidget
PageState
解决方案
我相信setState
应该只在小部件本身内调用。
在颤振中,谷歌在 Ephemeral 和 App State 之间做出了区分
https://flutter.dev/docs/development/data-and-backend/state-mgmt/ephemeral-vs-app
由于您希望您的登录是全局的,因此您需要 App State。
有很多方法可以管理它 - https://flutter.dev/docs/development/data-and-backend/state-mgmt/options
Redux - https://pub.dartlang.org/packages/flutter_redux
范围模型 - https://pub.dartlang.org/packages/scoped_model
集团 - https://felangel.github.io/bloc/#/
Mobx - https://github.com/mobxjs/mobx.dart
手动完成所有操作。
示例股票 - https://github.com/flutter/flutter/tree/master/examples/stocks
在孩子身上,你需要这个。
class StockSettings extends StatefulWidget {
const StockSettings(this.configuration, this.updater);
final StockConfiguration configuration;
final ValueChanged<StockConfiguration> updater;
@override
StockSettingsState createState() => StockSettingsState();
}
class StockSettingsState extends State<StockSettings> {
void _handleBackupChanged(bool value) {
sendUpdates(widget.configuration.copyWith(backupMode: value ? BackupMode.enabled : BackupMode.disabled));
}
void sendUpdates(StockConfiguration value) {
if (widget.updater != null)
widget.updater(value);
}
在父级中,您传递配置更新器,它只是设置状态的包装器
class StocksAppState extends State<StocksApp> {
StockData stocks;
StockConfiguration _configuration = StockConfiguration(
stockMode: StockMode.optimistic,
backupMode: BackupMode.enabled,
debugShowGrid: false,
debugShowSizes: false,
debugShowBaselines: false,
debugShowLayers: false,
debugShowPointers: false,
debugShowRainbow: false,
showPerformanceOverlay: false,
showSemanticsDebugger: false
);
@override
void initState() {
super.initState();
stocks = StockData();
}
void configurationUpdater(StockConfiguration value) {
setState(() {
_configuration = value;
});
}
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => StockHome(stocks, _configuration, configurationUpdater),
'/settings': (BuildContext context) => StockSettings(_configuration, configurationUpdater)
},
你的选择。
推荐阅读
- c# - 编译器问题,努力使用 Dispatcher.RunAsync() 调用 UI 线程并返回一个值
- flutter - 如何在 Flutter 中设置 CupertinoTextField 边框颜色?
- python - Python子进程在关闭stdin之前打开readline
- javascript - 为什么我的应用程序在任何操作上都会重新渲染?
- django - 我必须将客户数据转移到预订。任何可能的方法?请告诉我
- javascript - 如何更改数组的克隆而不更改reactjs中的原始数组
- ssis - 使用 SSIS 处理 Db 中的空单元格
- bots - 动态更改 Microsoft Teams 机器人名称和图标
- python - 为什么python会显示名称tk未定义的错误?
- android - 如何处理 Kotlin 中的 500 错误并使用 Retrofit2 显示详细消息?