我有一个实现接口的类
class _UserSignupInterface implements UserSignupInterface {
@override
void onSuccess() {
}
@override
void onError(String message) {
}
}
但是,我无法通过setState()更改变量,我将使用它来更改页面上显示的文本。
我试图将接口扩展到我的_SignupSelectUsernamePageState
并在接口内调用更改状态,但它只会导致错误,可能不应在接口内调用setState()。
我也尝试将变量放在StatefulWidget
和PageState
之外。但是,如果我不能在界面中使用setState(),那么简单地更新它的值就没有任何意义,因为它不反映更改页面上的文本。
该接口是我用于处理从网络请求接收的响应数据的回调。
在Text
和StatefulWidget
(扩展那个StatefulWidget)之外更改PageState
Widget文本的正确方法是什么?因为我必须在界面内处理数据处理和变量更新。
我相信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)
},
你的选择。