如何将弹出菜单按钮中的选定项目显示为文本?

问题描述 投票:0回答:1

我有一个弹出菜单按钮,其下方有一个文本小部件。我希望文本小部件显示用户从弹出菜单按钮中选择的内容。

Popup menu button unpressed Popup menu button pressed

现在在下面的

_mlTextWidget()
中,我只能弄清楚如何对特定选择进行硬编码。

我不确定如何将所选项目与文本小部件连接。任何帮助将不胜感激。

// A class containing the menu items
class MLConstants {
  static const String FourX = '4x';
  static const String TenX = '10x';
  static const String TwentyFiveX = '25x';
  static const String FourtyX = '40x';
  static const String SixtyThreeX = '63x';

  static const List<String> choices3 = <String>[
    FourX,
    TenX,
    TwentyFiveX,
    FourtyX,
    SixtyThreeX
  ];
}


// Popup menu button
Widget _cameraTogglesRowWidget() {
 return PopupMenuButton<String>(
      icon: const Icon(
        Icons.zoom_in,
        color: Colors.white,
        size: 30,
      ),
      onSelected: choiceAction3,
      itemBuilder: (BuildContext context) {
        return MLConstants.choices3.map((String choice3) {
          return PopupMenuItem<String>(
            value: choice3,
            child: Text(choice3),
          );
        }).toList();
      },
    );
  }


// What happens when a menu item is pressed
  void choiceAction3(String choice3) {
    if (choice3 == MLConstants.FourX) {
      print('4x');
    } else if (choice3 == MLConstants.TenX) {
      print('10x');
    } else if (choice3 == MLConstants.TwentyFiveX) {
      print('25x');
    } else if (choice3 == MLConstants.FourtyX) {
      print('40x');
    } else if (choice3 == MLConstants.SixtyThreeX) {
      print('63x');
    }
  }


// The text widget showing the selected item
  Widget _mlTextWidget() {
    return Container(
        child: (Text("${MLConstants.FourX}",
            style: TextStyle(
              fontSize: 13,
              color: Colors.white,
            ))));
  }
flutter dart
1个回答
0
投票

您需要将其置于

onSelected
状态并在您的
Text
中使用它。像这样:

  String selectedChoice3;

  void choiceAction3(String choice3) {
    setState(() {
      selectedChoice3 = choice3;
    });
    if (choice3 == MLConstants.FourX) {
      print('4x');
    } else if (choice3 == MLConstants.TenX) {
      print('10x');
    } else if (choice3 == MLConstants.TwentyFiveX) {
      print('25x');
    } else if (choice3 == MLConstants.FourtyX) {
      print('40x');
    } else if (choice3 == MLConstants.SixtyThreeX) {
      print('63x');
    }
  }


// The text widget showing the selected item
  Widget _mlTextWidget() {
    return Container(
        child: (Text("${selectedChoice3 ?? ''}",
            style: TextStyle(
              fontSize: 13,
              color: Colors.white,
            ))));
  }

当然,假设这些是在

State
类中。如果没有,您可以在
IntelliJ
VSCode
中自动将 StatelessWidget 转换为 StatefulWidget

© www.soinside.com 2019 - 2024. All rights reserved.