简体   繁体   English

更改 DropDownButton 时如何更改变量

[英]How to change a variable when changing DropDownButton

I have 3 variables containing text that I can pass to message .我有 3 个变量,其中包含可以传递给message的文本。

String easyDrop = 'All ok';
String mediumDrop = '1 problem';
String hardDrop = 'All not ok';

message: easyDrop ,

I would like to change them depending on the state of my DropDownButton.我想根据我的 DropDownButton 的 state 更改它们。 How can I do this?我怎样才能做到这一点?

import 'package:flutter/material.dart';

class DropDownButtonDifficultySettingsWidget extends StatefulWidget {
  DropDownButtonDifficultySettingsWidget({Key? key}) : super(key: key);

  @override
  State<DropDownButtonDifficultySettingsWidget> createState() => _DropDownButtonDifficultySettingsState();
}

class _DropDownButtonDifficultySettingsState extends State<DropDownButtonDifficultySettingsWidget> {
  String dropdownValue = 'Medium';

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
       splashColor: Colors.blue.withOpacity(0.4),),
      child: DropdownButton<String>(
        value: dropdownValue,
        elevation: 8,
        alignment: Alignment.centerRight,
        iconDisabledColor: Colors.blue,
        iconEnabledColor: Colors.blue,
        underline: Container(
             height: 0,
        ),
        style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w500, ),
        onChanged: (String? newValue) {
          
          setState(() {
            dropdownValue = newValue!;
          });
        },
        items: <String>['Easy', 'Medium', 'Hard']
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }
}

You can include a callback method to get selected item from DropDownButtonDifficultySettingsWidget您可以包含一个回调方法以从DropDownButtonDifficultySettingsWidget获取所选项目

class DropDownButtonDifficultySettingsWidget extends StatefulWidget {
  final Function(String? selectedValue) callback;
  const DropDownButtonDifficultySettingsWidget(
      {Key? key, required this.callback})
      : super(key: key);

  @override
  State<DropDownButtonDifficultySettingsWidget> createState() =>
      _DropDownButtonDifficultySettingsState();
}

And on changed并改变了

onChanged: (String? newValue) {
  setState(() {
    dropdownValue = newValue!;
  });
  widget.callback(dropdownValue); //this
},

Now when ever you use DropDownButtonDifficultySettingsWidget you will get selected value on callback现在,当您使用DropDownButtonDifficultySettingsWidget时,您将在回调中获得选定的值

DropDownButtonDifficultySettingsWidget(
  callback: (selectedValue) {
    print(selectedValue);
/// do the thing you like to have 
  },
),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM