首页 > 解决方案 > 如何在没有 StatefulWidget 的情况下使用 setState?

问题描述

首先,我知道这样做并不是真的可行,但我有一个问题,我不知道该怎么做。我想使用 DropDown 但它不会在没有 setState 的情况下更改文本,而且我无法将此代码转换为 StatefulWidget。我该怎么办?代码并不重要,但在这里(不是整个代码):

  Widget buildAboutDialog(
      BuildContext context, _myHomePageState, bool isEdit, Clothes clothes){
    if(clothes != null){
      this.clothes = clothes;
      teCategoryName = clothes.category;
      teBrandName.text = clothes.brand;
      teColorName.text = clothes.color;
      teSizeName.text = clothes.size;
      teQtyName.text = clothes.qty;
    }
   return new AlertDialog(
      title: new Text(isEdit ? 'Edit' : 'Add new Clothes'),
      content: new SingleChildScrollView(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(

              child: Center(
                child: DropdownButton(
                  hint:  Text("Choose Category"),
                  value: teCategoryName,
                  isExpanded: true,
                  onChanged: (newValue){
                    teCategoryName = newValue;
                    **setState(() {
                      teCategoryName = newValue;
                    });**

                  },
                  items: _categorynames.map((location){
                    return DropdownMenuItem(
                      child: new Text(location),
                      value: location,
                    );
                  }).toList(),

                ),
              ),
            ),

标签: android-studioflutterdart

解决方案


你不能。

setState方法更新小部件的状态。A StatelessWidget,根据定义,没有要更新的状态。因此,如果您希望能够调用setState,则需要将您的小部件转换为StatefulWidget. (但是,是的,anyStatelessWidget可以很容易地转换为StatefulWidget.)


推荐阅读