gpt4 book ai didi

android - 更改最终变量的值

转载 作者:行者123 更新时间:2023-12-03 04:32:34 24 4
gpt4 key购买 nike

我有两个文件。在第二个文件中,我有两个类-StatefulWidget和State。
files1.dart:

(...)
Clothes _myClothes;
Widget _buildForm() {
return ClothesForm(clothes: _myClothes);
}
(...)
我要从另一个文件向StatefulWidget类发送衣服变量,即Clothing对象。
文件2:
class ClothesForm extends StatefulWidget {
final Clothes clothes;

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



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

}
在State类中,我想更改衣服变量的值-例如widget.clothes.color = red,以便发送此变量的文件也看到此更改。
class _ClothesFormState extends State<ClothesForm> {
widget.clothes.color = red
}
显然,我不能这样做,因为它是一个最终变量。
问题-我该如何做才能使更改在原始file1中可见并且变量_myClothes具有新值?

最佳答案

这是一种解决方法...
这个怎么运作:

  • ClothesForm中使用Clothe参数创建一个回调函数。
  • 每当您想更新/更改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);
    }
    );
    }
    (...)

    关于android - 更改最终变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64687996/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com