更改最终变量的值

Change the value of the final variable

我有两个文件。在第二个文件中,我有两个 classes - StatefulWidget 和 State.

files1.dart:

(...)
Clothes _myClothes;
Widget _buildForm() {
    return ClothesForm(clothes: _myClothes);
  }
(...)

我正在从另一个文件向 StatefulWidget class 发送 clothes 变量,它是 Clothing 对象。

文件 2:

class ClothesForm extends StatefulWidget {
 final Clothes clothes;

  const ClothesForm({Key key, this.clothes
  }) : super(key: key);



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

在状态 class 中,我想更改变量 clothes 的值 - 例如 widget.clothes.color = red,以便发送此变量的文件也能看到此更改。

class _ClothesFormState extends State<ClothesForm> {
   widget.clothes.color = red
}

显然,我不能这样做,因为它是一个最终变量。

问题 - 我如何才能使更改在原始文件 1 中可见并且变量 _myClothes 具有新值?

这是一个解决方法...

工作原理:

  • ClothesForm.
  • 中创建一个带有 Clothe 参数的回调函数
  • 随时调用该函数 update/change clothes 以便更改在文件 1 中可见。
  • 执行你的文件1中的函数并将_myClothes设置为衣服(函数的参数)。

实施

class ClothesForm extends StatefulWidget {
 final Clothes clothes;
 final Function(Clothes clothes) onUpdateClothe;

  const ClothesForm({Key key, this.clothes, this.onUpdateClothe
  }) : super(key: key);



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

class _ClothesFormState extends State<ClothesForm> {
   widget.clothes.color = red

   @override
   void initState(){
     super.initState();
     Clothes clotheUpdate = widget.clothes..color = red;
     widget.onUpdateClothe(clotheUpdate);
   }
}
(...)
Clothes _myClothes;
Widget _buildForm() {
    return ClothesForm(
          clothes: _myClothes,
          onUpdateClothe: (newClothe){
               setState(() => _myClothes = newClothe);
          }
    );
  }
(...)