【问题标题】:How to do operations on state constructor variables in Flutter?Flutter中如何对状态构造函数变量进行操作?
【发布时间】:2021-06-30 04:56:14
【问题描述】:

我想在 homeWidget 中显示 wordCount 的变化

    return Scaffold(
      body: Column(
        children: [
          ...
          Expanded(
            flex: 1,
            child: RecorderView(
              onSaved: _onRecordComplete,
              wordCount:wordCount,
            ),
          ),
        ],
      ),
    );

变量wordCount依赖RecordView方法:

我写这个是为了在这里获取状态变量

class RecorderView extends StatefulWidget {
  final Function onSaved;
  final int wordCount;
  const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
  @override
  _RecorderViewState createState() => _RecorderViewState();
}

class _RecorderViewState extends State<RecorderView> {

//in one method
    widget.wordCount++;
}

我想在此处添加 wordCount,但它说这是最后一个。如果没有 final,我如何从 homeWidget 继承 wordCount?我只是想自动更改wordCount中显示的单词,谢谢!!

【问题讨论】:

  • 您需要提升状态或进行更高级的状态管理。查看 InheritedWidget 了解 Flutter 框架方法,或提供者之类的方法

标签: flutter state setstate


【解决方案1】:

您不能继承该变量,但是可以将其初始化为小部件中的值。

class RecorderView extends StatefulWidget {
  final Function onSaved;
  final int wordCount;
  const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
  @override
  _RecorderViewState createState() => _RecorderViewState();
}

class _RecorderViewState extends State<RecorderView> {
int _wordCount;

@override
void initState() {
super.initState();
_wordCount = widget.wordCount;
}
}

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多