enter image description here

我正在try 使下拉菜单具有与TextFormfield相同的大小.我怎么能这样做呢?

我试过使用MediaQuery,但它占据了整个屏幕.

我不确定该如何处理这种情况.

我也try 过使用Width,例如Width:300,但我不确定这是否适用于所有设备,所以我正在寻找一个通用的解决方案.




import 'package:flutter/material.dart';

const List<String> list = <String>['One', 'Two', 'Three', 'Four'];

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Raporteaza o problema'),
        ),
        body: MyCustomForm(),
      ),
    );
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Define a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a `GlobalKey<FormState>`,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  String dropdownValue = list.first;

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: TextFormField(
              // The validator receives the text that the user has entered.
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              decoration: const InputDecoration(
                labelText: 'Nume și prenume',
                border: OutlineInputBorder(),
                hintText: 'Nume și prenume',
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: TextFormField(
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Te rog introdu o adresă de email.';
                } else if (!RegExp(
                        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                    .hasMatch(value)) {
                  return 'Te rog introdu o adresă de email validă.';
                }
                return null;
              },
              decoration: const InputDecoration(
                labelText: 'Email',
                border: OutlineInputBorder(),
                hintText: 'example@example.com',
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
            child: DropdownMenu<String>(,
              initialSelection: list.first,
              onSelected: (String? value) {
                // This is called when the user selects an item.
                setState(() {
                  dropdownValue = value!;
                });
              },
              dropdownMenuEntries:
                  list.map<DropdownMenuEntry<String>>((String value) {
                return DropdownMenuEntry<String>(value: value, label: value);
              }).toList(),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              // Validate returns true if the form is valid, or false otherwise.
              if (_formKey.currentState!.validate()) {
                // If the form is valid, display a snackbar. In the real world,
                // you'd often call a server or save the information in a database.
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Processing Data')),
                );
              }
            },
            child: const Text('Submit'),
          ),
        ],
      ),
    );
  }
}

推荐答案

试试这个:

import 'package:flutter/material.dart';

const List<String> list = <String>['One', 'Two', 'Three', 'Four'];

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Raporteaza o problema'),
        ),
        body: MyCustomForm(),
      ),
    );
  }
}

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

  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

class MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();
  String dropdownValue = list.first;

  // GlobalKey instances for the TextFormFields
  final GlobalKey<FormState> _nameKey = GlobalKey<FormState>();
  final GlobalKey<FormState> _emailKey = GlobalKey<FormState>();

  double dropdownWidth = 0.0; // Store the width for the dropdown menu

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: TextFormField(
              key: _nameKey,
               validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              decoration: const InputDecoration(
                labelText: 'Nume și prenume',
                border: OutlineInputBorder(),
                hintText: 'Nume și prenume',
              ),
              // ... your TextFormField properties
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: TextFormField(
              key: _emailKey,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Te rog introdu o adresă de email.';
                } else if (!RegExp(
                        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                    .hasMatch(value)) {
                  return 'Te rog introdu o adresă de email validă.';
                }
                return null;
              },
              decoration: const InputDecoration(
                labelText: 'Email',
                border: OutlineInputBorder(),
                hintText: 'example@example.com',
              ),
              // ... your TextFormField properties
            ),
          ),
          Padding(
             padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: LayoutBuilder(
              builder: (context, constraints) {
                dropdownWidth = constraints.maxWidth; // Set dropdownWidth to match the width of the TextFormFields
                return DropdownMenu<String>(
                  width: dropdownWidth,
                  initialSelection: list.first,
                  onSelected: (String? value) {
                    setState(() {
                      dropdownValue = value!;
                    });
                  },
                  dropdownMenuEntries: list.map<DropdownMenuEntry<String>>((String value) {
                    return DropdownMenuEntry<String>(value: value, label: value);
                  }).toList(),
                );
              },
            ),
          ),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Processing Data')),
                );
              }
            },
            child: const Text('Submit'),
          ),
        ],
      ),
    );
  }
}

Flutter相关问答推荐

底部导航栏项目在抖动中不更改 colored颜色

你能go 掉Flutter 小部件测试中的样板吗?

Flutter :在后台实现振动

带有图标抖动的自定义下拉按钮

GetConnect Post API调用在Flutter Web中不起作用说:415不支持的媒体类型

Flutter中的编译时间常量方法

Flutter Xcode 15 错误(Xcode):DT_TOOLCHAIN_DIR 无法用于判断 LIBRARY_SEARCH_PATHS

模块是使用不兼容的 kotlin 版本编译的.其元数据的二进制版本是1.8.0,预期版本是1.6

Flutter如何从深入嵌套的小部件中打开抽屉?

如何设置行中项目之间的空格相等?

为什么我们使用 RiverpodGenerator

将状态维护到 asyncNotifier

我的第一个 flutter 项目出错,启动时为空值?

如何使用 riverpod_annotation 创建非自动处置提供程序?

Cloud firestore:如何使用 map 对象创建和更新嵌套数组

如何使用 Rrect 或类似工具在 flutter 中绘制梯形线?

按下 Command+W 时关闭窗口

Flutter中如何连续获取TextField的文本是否为空?

Flutter 如何要求用户在应用程序中设置电话密码?

如何在dart中编写多个条件?