如何获得Flutter中的currentState?

问题描述 投票:0回答:1

我想通过我的模型将我的List数据推送到数据库,并且我想获取我的currentState。

class SettingsDialog extends StatefulWidget {
  final ChexiUser user;

  SettingsDialog({this.user});
  @override
  _SettingsDialogState createState() => _SettingsDialogState();
}

这里是我的有状态小部件,它创建了一个可变的小部件_SettingsDialogState。我有一个名为Options的类,它具有一个静态列表函数getOptions(user)来将我的选项映射到DataTable上。

class Option {
  String name;
  String option;
  String description;
  bool value;
  Object user;
  String valueString;

  Option(
    {this.name,
     this.option,
     this.description,
     this.user,
     this.value,
     this.valueString});

 static List<Option> getOptions(user) {
   return <Option>[
   Option(
      name: 'autoPass',
      value: user.settingsAutoPass,
      option: 'Auto Pass',
      description:
          'The game will automatically roll the dice when a new turn starts or a double is rolled'),
   Option(
      name: 'autoRoll ',
      value: user.settingsAutoRoll,
      option: 'Auto Roll',
      description:
          'The game will automatically pass the dice if there is no move'),
    Option(
      name: 'showCheckMoves ',
      value: user.settingsShowCheckMoves,
      option: 'Show Check Move',
      description:
          'When an opponent can be put in check, highlight the squares (from, to) that will lead to a 
      check '),
    Option(
      name: 'showFileRank ',
      value: user.settingsShowFileRank,
      option: 'Show File Rank',
      description:
          'Show the files and ranks on the sides of the gameboard'),
  Option(
      name: 'showLastOpponentMove',
      value: user.settingsShowLastOpponentMove,
      option: 'Show Last Opponent Move',
      description:
          ' The opponent\'s last move (from, to) will show as a different colored square'),
    Option(
      name: 'showMateMoves',
      value: user.settingsShowMateMoves,
      option: 'Show Mate Move',
      description:
          'When an opponent can be put in mate, highlight the squares (from,to) that will lead to a 
      mate'),];
  }
}

在我的_SettingsDialogState类小部件中,我已经初始化了选项

class _SettingsDialogState extends State<SettingsDialog> {
  List<Option> options;

@override
void initState() {
  options = Option.getOptions(widget.user);
  super.initState();
}

现在在我的数据表上,每当有更改以更新我的initState的值时,我都调用setState((){}),并且它运行良好。现在,我希望将数据保存在模型函数中,并且需要状态数据,并且我不知道如何获取数据。我应该将选项列表传递给我的保存功能还是只调用小部件的currentState。我被困住了,一直在网上寻找解决方案。我尝试传递选项列表,但在打印出来时会调用Option实例。我需要您的专业知识。谢谢大家,我知道我已经接近了,我只需要知道如何执行。还是我关闭?

flutter flutter-layout
1个回答
0
投票

避免静态初始化变量。

  options = Option.getOptions(widget.user);

相反,将其定义为小部件中的变量,并使用构造函数分配值。

class SettingsDialog extends StatefulWidget {
  final ChexiUser user;
  final List<Option> options;


  SettingsDialog({this.user,this.options});
  @override
  _SettingsDialogState createState() => _SettingsDialogState();
}

在状态类中,您可以使用widget.options访问该值。

© www.soinside.com 2019 - 2024. All rights reserved.