dart 下拉菜单在选项单击后不更新

5us2dqdw  于 2023-09-28  发布在  其他
关注(0)|答案(2)|浏览(155)

我做了一个简单的类来存储我的下拉选项:

class ExperienceYearsRepository {
  List<String> returnExperienceYears() {
    return [
      "Menos de 1 ano",
      "Entre 1 e 3 anos",
      "Entre 3 e 5 anos",
      "Mais de 5 anos"
    ];
  }
}

下面有一个使用该列表的下拉实现,但是当单击任何选项时,下拉列表中显示的值始终是设置为experienceYears.first的值:

String experienceTime = "";
var experienceYearsRepository = ExperienceYearsRepository();
var experienceYears = [];

void initState() {
   experienceYears = experienceYearsRepository.returnExperienceYears();
   super.initState();
}

DropdownButton(
   isExpanded: true,
   value: experienceYears.first,
   items: experienceYears
       .map((experienceYear) => DropdownMenuItem(
             value: experienceYear,
             child: Text(experienceYear.toString()),
           ))
       .toList(),
   onChanged: (selectedExperienceTime) {
     setState(() {
        debugPrint(selectedExperienceTime as String?);
        experienceTime = selectedExperienceTime.toString();
     });
   }),

澄清一下,debugPrint实际上打印了正确的下拉列表项,所以问题在于显示它。有什么解决办法吗?我对Flutter很陌生,我很头疼,提前感谢!

2w2cym1i

2w2cym1i1#

String experienceTime = "";
var experienceYearsRepository = ExperienceYearsRepository();
var experienceYears = [];

void initState() {
experienceYears = experienceYearsRepository.returnExperienceYears();
  experienceTime = experienceYears.first; //assign here
super.initState();
}

DropdownButton(
 isExpanded: true,
 value: experienceTime, //use here
 items: experienceYears
   .map((experienceYear) => DropdownMenuItem(
         value: experienceYear,
         child: Text(experienceYear.toString()),
       ))
   .toList(),
  onChanged: (selectedExperienceTime) {
 setState(() {
    debugPrint(selectedExperienceTime as String?);
    experienceTime = selectedExperienceTime.toString();
 });
 }),
ecbunoof

ecbunoof2#

DropdownButton()的value属性不仅仅用于初始化,它是当前显示在菜单上的值。更改onChanged参数以更新它。你可以在init()方法中指定它。

@override
void initState() {
    experienceYears = experienceYearsRepository.returnExperienceYears();
    experienceTime = experienceYears.first; //move initialization here
    super.initState();
}

   DropdownButton(
      isExpanded: true,
      value: experienceTime,   //controlling variable
      items: experienceYears
          .map((experienceYear) => DropdownMenuItem(
                value: experienceYear,
                child: Text(experienceYear.toString()),
              ))
          .toList(),
      onChanged: (selectedExperienceTime) {
        setState(
          () {
            debugPrint(selectedExperienceTime as String?);
            experienceTime = selectedExperienceTime.toString(); //update it here
          },
        );
      },
    ),

相关问题