发生异常,_AssertionError('package:flutter/src/material/dropdown. dart':Assert失败:第882行位置15:'项目== null|| items.isEm

lb3vh1jj  于 2023-05-23  发布在  Flutter
关注(0)|答案(2)|浏览(280)
Exception has occurred.
_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 882 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1': There should be exactly one item with [DropdownButton]'s value: 1. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)

我有这个错误,而我试图张贴1如果选择的下拉菜单是'全职',2如果选择的下拉菜单是'兼职和3如果选择的下拉菜单是'实习

DropdownButton(
              hint: Text("Select Job type"),
              value: currentValue,
              isDense: true,
              icon: const Icon(Icons.keyboard_arrow_down),
              items: <String>[
                if (currentValue == "1")
                  ("Full-time")
                else if (currentValue == "2")
                  ("Part-time")
                else
                  "Internship",
              ].map((String i) {
                return DropdownMenuItem(
                  value: i,
                  child: Text(i),
                );
              }).toList(),
              onChanged: onChangedCallback,
            ),

我的onChangedCallback如下所示
var currentValue =“1”;

Future<void> onChangedCallback(String? item) async {
    if (item != null) {
      currentValue = item;
      final url = "my-api-link";
      final body = {"job_type": item};
      final response = await http.post(Uri.parse(url), body: body);
      print(response.body);
    }
  }
jc3wubiy

jc3wubiy1#

试试这个:

String? currentValue;
var _dropdownItems = <String>['Full-time', "Part-time", "Internship"];
// put the following inside initState() or build()
// start
_dropdownMenuItems = _dropdownItems
        .map((String value) =>
            DropdownMenuItem(child: Text(value), value: value))
        .toList();
// end
DropdownButton(
  hint: Text("Select Job type"),
  value: currentValue,
  isDense: true,
  icon: const Icon(Icons.keyboard_arrow_down),
  items: _dropdownMenuItems,
  onChanged: onChangedCallback,
);
/* ... */
Future<void> onChangedCallback(String? item) async {
  if (item != null) {
    // change this:
    // setState(() => currentValue = item);
    // to: 
    setState(() => currentValue = _dropdownItems.indexOf(item!).toString());
    //
    final url = "my-api-link";
    final body = {"job_type": item};
    final response = await http.post(Uri.parse(url), body: body);
    print(response.body);
  }
}
oug3syen

oug3syen2#

在下拉菜单中填充项目参数之前,必须设置“值”参数。
参考下面的例子,其中'dropdownValue'被初始化为'list.first',因为这个我得到了异常。

import 'package:flutter/material.dart';

/// Flutter code sample for [DropdownButton].

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

void main() => runApp(const DropdownButtonApp());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('DropdownButton Sample')),
        body: const Center(
          child: DropdownButtonExample(),
        ),
      ),
    );
  }
}

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

  @override
  State createState() => _DropdownButtonExampleState();
}

class _DropdownButtonExampleState extends State {
  String dropdownValue = list.first;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      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>((String value) {
        return DropdownMenuItem(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}

相关问题