首页 > 解决方案 > 这个类被标记为“@immutable”,但它的一个或多个实例字段不是最终的:

问题描述

如果我将变量声明为最终变量,那么我想要更改(按下时)的值(变量)就在其中,setState(){}因此可以更改这些变量如何防止这种情况发生?

还有,为什么要写widget.value

我尝试使用 static 而不是 final 不起作用

class BottomCard extends StatefulWidget {

String title;

int value;
@override
_BottomCardState createState() => _BottomCardState(); }

class _BottomCardState extends State<BottomCard> {..... 


....<Widget>[  
        FloatingActionButton(
          elevation: 0,
          child: Icon(FontAwesomeIcons.plus),
          onPressed: () {
            setState(() {
              widget.value++;
            });
          },
          backgroundColor: Color(0xFF47535E),
        ),

标签: classflutterdartflutter-layoutsetstate

解决方案


如果您不需要从外部类获取变量(标题和值)。您可以在 _BottomCardState 课堂上声明它们并根据需要使用它们。喜欢这段代码。

class BottomCardState extends StatefulWidget {
  @override
  _BottomCardStateState createState() => _BottomCardStateState();
}

class _BottomCardStateState extends State<BottomCardState> {
  int _value;
  String title;

  @override
  void initState() {
    super.initState();
    _value = 0;
    title = "any thing";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        elevation: 0,
        child: Icon(FontAwesomeIcons.plus),
        onPressed: () {
          setState(() {
            _value++; // increment value here
          });
        },
      ),
    );
  }
}

如果您需要从其他类中获取变量(值和标题)。那么您需要将它们标记为 final 1。2-从构造函数中获取它们并访问它们的值,_BottomCardStateState您需要使用它们来访问它们。它们widget._value是最终的,您无法修改它们。喜欢这里的代码

class App extends StatelessWidget {
  const App({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: BottomCardState(2,"some thing"),
    );
  }
}

class BottomCardState extends StatefulWidget {
  final int _value;
  final String title;
  BottomCardState(this._value,this.title)

  @override
  _BottomCardStateState createState() => _BottomCardStateState();
}

class _BottomCardStateState extends State<BottomCardState> {
  int value ;
  @override
  Widget build(BuildContext context) {
    value = widget._value ;
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        elevation: 0,
        child: Icon(FontAwesomeIcons.plus),
        onPressed: () {
          setState(() {
          value++; // increment value here
          });
        },
      ),
    );
  }
}

推荐阅读