首页 > 解决方案 > 如何从界面设置状态?

问题描述

我有一个实现接口的类

class _UserSignupInterface implements UserSignupInterface {
  @override
  void onSuccess() {

  }

  @override
  void onError(String message) {
  }
}

但是,我无法通过 setState() 更改变量,我将使用它来更改页面上显示的文本。

我试图将接口扩展到我的接口_SignupSelectUsernamePageState并在接口内调用更改状态,但这只会导致错误,也许 setState() 不应在接口内调用。

我也尝试将变量放在StatefulWidget和之外PageState。但是,如果我不能在界面内使用 setState() ,那么简单地更新它的值就没有任何意义,因为它不会反映更改页面上的文本。

该接口是我用来处理从网络请求接收到的响应数据的回调。

在and (扩展 StatefulWidget)Text之外更改 Widget 文本的正确方法是什么?因为我必须处理界面内的数据处理和变量更新。StatefulWidgetPageState

标签: interfacedartflutter

解决方案


我相信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)
},

你的选择。


推荐阅读