0

这是我的代码,我不知道为什么提示没有改变,当我单击选项时,显然所有这些代码都在一个类中,我尝试使用 for 循环来识别列表位置,如果它们是正确的,它会出现在屏幕上。

final listgenre = ["Masc", "Fem", "Não Binário"];
var listgenre_value;
String newValue = "";
var valueChoose;
String hintValue = "";
   Padding(
                padding: EdgeInsets.all(16),
                child: Container(
                    padding: EdgeInsets.only(left: 16, top: 10, right: 15),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 2),
                        borderRadius: BorderRadius.circular(20)),
                    child: DropdownButton<String>(
                      hint: Text("Genero :$hintValue"),
                      dropdownColor: Colors.white,
                      icon: Icon(Icons.arrow_drop_down),
                      iconSize: 36,
                      iconEnabledColor: Colors.black,
                      isExpanded: true,
                      style: TextStyle(fontSize: 17, color: Colors.black),
                      value: valueChoose,
                      underline: SizedBox(
                        width: 320,
                        height: 200,
                      ),
                      items: listgenre.map((valueitem) {
                        return DropdownMenuItem(
                          value: valueitem,
                          child: Text(valueitem),
                        );
                      }).toList(),
                      onChanged: (newValue) {
                        setState(() {
                          for (int i = 0; i <= listgenre.length; i++) {
                            if (listgenre[i] != newValue) {
                              listgenre_value = i + 1;
                            } else {
                              hintValue = "$newValue";
                              // ignore: void_checks
                              return listgenre_value;
                            }
                          }

                          Object? valueChoose = newValue;
                          String valueChoosen = valueChoose.toString();
                        });
                      },
                    ))),
4

1 回答 1

0

根据您的评论,相同的代码没有给出预期的输出。

仅当您还在构建方法中初始化变量时才有可能但情况并非如此。

不正确的代码

@override
  Widget build(BuildContext context) {
    
    // ---- your variables INSIDE build method

    final listgenre = ["Masc", "Fem", "Não Binário"];
    var listgenre_value;
    String newValue = "";
    var valueChoose;
    String hintValue = "";

// ------- rest of the code continued

正确的代码

  final listgenre = ["Masc", "Fem", "Não Binário"];
  var listgenre_value;
  String newValue = "";
  var valueChoose;
  String hintValue = "";

  @override
  Widget build(BuildContext context) {

  // ------- rest of the code continued

由于build每次调用该方法都setState被调用,hintValue因此被初始化为""空字符串。

于 2021-07-12T13:59:04.223 回答