如何根据所选项目动态调整Flutter DropdownButton宽度?

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

我正在开发一个 Flutter 应用程序,我正在尝试创建一个

DropdownButton
,根据所选项目文本的长度调整其宽度。我希望下拉菜单与所选项目一样宽,而不是列表中最宽的项目。此功能类似于本机 HTML
select
元素,其中宽度根据当前所选选项动态调整大小。

这是我当前代码的简化版本:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedValue;
  final List<String> options = ['Apple', 'Banana', 'Cherry', 'Fig'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DropdownButtonHideUnderline(
          child: DropdownButton<String>(
            value: selectedValue,
            items: options.map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            onChanged: (newValue) {
              setState(() {
                selectedValue = newValue;
              });
            },
          ),
        ),
      ),
    );
  }
}

下拉菜单始终采用列表中最宽项目的宽度。但是,我希望下拉列表仅适合所选项目的宽度,类似于此中显示的行为

我尝试使用 ButtonTheme 和alignedDropdown: true 并在 DropdownButton 上设置 isDense: true,但它没有产生所需的结果。

Flutter 中是否真的可以有一个 DropdownButton 根据所选项目自动调整其宽度?如果是这样,我怎样才能实现这种行为?

任何建议或解决方法将不胜感激!

android flutter hybrid-mobile-app
1个回答
0
投票
DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: selectedValue,
              // Change this Alignment
              alignment: AlignmentDirectional.centerEnd,
              items: options.map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
              onChanged: (newValue) {
                setState(() {
                  selectedValue = newValue;
                });
              },
            ),
          ),
© www.soinside.com 2019 - 2024. All rights reserved.