flutter 复位下拉菜单抖动

ar7v8xwq  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(160)

按下按钮后如何将dropdown复位到默认值?
我尝试到按按钮到复位dropdownmune到它的defualt

class drawarScreen extends StatelessWidget {
  const drawarScreen({super.key});

  @override
  Widget build(BuildContext context) {
List<String> list = <String>['One', 'Two', 'Three', 'Four'];
  String? dropdownValue;
    
    return  Scaffold(
        body: Column(children:[

DropdownButton<String>(
      hint: Text('moammed'),
      value: dropdownValue,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String? value) {
        // This is called when the user selects an item.
          setstate({
        dropdownValue = value!;
});
        
      },
      items: list.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  },
ElevatedButton(
onPress:(){
setstate({
dropdownValue='';
});

},child: Text("reste");
)
]);

  }
}

我尝试到按按钮到复位dropdownmune到它的defualt
Flutter中的复位下拉菜单

djmepvbi

djmepvbi1#

您需要放置空值而不是空字符串

setstate({
  dropdownValue = null ;
});

如果你不喜欢null,就把它放在那里,并且确保在build方法之外有StatefulWidget和变量。
完整小部件

class drawarScreen extends StatefulWidget {
  const drawarScreen({super.key});

  @override
  State<drawarScreen> createState() => _drawarScreenState();
}

class _drawarScreenState extends State<drawarScreen> {
  List<String> list = <String>['One', 'Two', 'Three', 'Four'];
  String? dropdownValue;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          DropdownButton<String>(
            hint: Text('moammed'),
            value: dropdownValue,
            icon: const Icon(Icons.arrow_downward),
            elevation: 16,
            style: const TextStyle(color: Colors.deepPurple),
            underline: Container(
              height: 2,
              color: Colors.deepPurpleAccent,
            ),
            onChanged: (String? value) {
              setState(() {
                dropdownValue = value;
              });
            },
            items: list.map<DropdownMenuItem<String>>((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
          ),
          ElevatedButton(
              onPressed: () {
                setState(() {
                  dropdownValue = null;
                });
              },
              child: Text("Reset"))
        ],
      ),
    );
  }
}

相关问题