【问题标题】:Problem with commiting a String to a Stateful Widget将字符串提交到有状态小部件的问题
【发布时间】:2021-05-15 13:51:00
【问题描述】:

我想创建一个 ModalBottomSheet,它会打开很多 RaisedButton。这些按钮应该在按下后改变颜色。 因此,我创建了一个名为“Buttons”的 StatefulWidget。

在我的 MainClass 中,我使用 for (String item in myList) Buttons(item)

将 myList 的字符串提交给按钮。

但我在按钮上有 2 个问题:

  1. String item 应该是最终的,但是我不能将它用作二传手 (我想去掉 Buttons 的蓝色下划线,它告诉我:这个类(或这个类继承自的类)被标记为“@immutable”,但它的一个或多个实例字段不是最终的: )

  2. 另一个问题是,在我的 buildMethod 中没有定义“item”。 为什么我的构建方法中不能使用String item

 class Buttons extends StatefulWidget {
  String item;
  Buttons(String item) {
    this.item = item;
  }

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

class _ButtonsState extends State<Buttons> {
  bool pressAttention = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Card(
        child: RaisedButton(
          child: Text(item),
          color: pressAttention ? Colors.grey : Colors.blue,
          onPressed: () => setState(() => pressAttention = !pressAttention),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    Text(item) 替换为Text(widget.item)

    class Buttons extends StatefulWidget {
      final String item;
      Buttons(this.item);
    
      @override
      _ButtonsState createState() => _ButtonsState();
    }
    
    class _ButtonsState extends State<Buttons> {
      bool pressAttention = false;
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Card(
            child: RaisedButton(
              child: Text(widget.item),
              color: pressAttention ? Colors.grey : Colors.blue,
              onPressed: () => setState(() => pressAttention = !pressAttention),
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 谢谢它有效。但我不太清楚为什么它会这样工作
    • 那是因为您在widgetstate 中,但不在widget 中。
    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2020-10-18
    • 2021-05-19
    • 2021-09-21
    • 2019-12-20
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多