繁体   English   中英

如何更改 Flutter 中的 DropdownMenuItem? (断言失败)

[英]How do i change a DropdownMenuItem in Flutter? (Failed assertion)

我正在尝试使用我的 Colorpicker 中最近使用的 Colors 构建一个下拉菜单。 因此我得到了一个带有 DropdownMenuItems 的列表:

static Color recentUsedColor1;
...(5 of them)
List<DropdownMenuItem<Color>> recentUsedColors = [
    DropdownMenuItem(
      child: Container(height: 20,width: 20,color: recentUsedColor1,),
      value: recentUsedColor1,
    ),
    ...(5 of them) ];

和我的构建方法中的下拉按钮:

``

DropdownButton(
                value: recentUsedColor1,
                items: recentUsedColors,
                onChanged: (value) {
                  setState(() {
                    brushColor = value;
                  });
                },
              ),``

现在,如果选择了一种新颜色,我将旧颜色放在 recentUsedColor1 变量中:

``ColorPicker(
    color: Colors.blue,
    onChanged: (value) {
    setState(() {
      recentUsedColor1 = brushColor;
      brushColor = value;
                                      });
                                    })

``

但不知何故,我瞬间得到了错误我 select 在我的颜色选择器中出现了一种新颜色(在我尝试更改变量 recentUsedColor1 的那一刻),我不明白为什么。

详细错误:

I/flutter ( 3095): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════

The following assertion was thrown building Grid(dirty, dependencies: [MediaQuery, LocalizationsScope-[GlobalKey#0922e], _InheritedTheme], state: GridState#ea90e):

'package:flutter/src/material/dropdown.dart': Failed assertion: line 620 pos 15: 'items == null ||
items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==
value).length == 1': is not true.

错误意味着 recentUsedColors 不是初始化或为空

items: recentUsedColors,

不知道你用的是什么颜色选择器。 但概念是一样的
使用List<Color>记录历史颜色并生成 DropdownButton

代码片段

DropdownButton<Color>(
                    //isDense: true,
                    hint: Text('Choose a goal category'),
                    value: dropdownValue,
                    icon: Icon(Icons.check_circle_outline),
                    iconSize: 24,
                    elevation: 16,
                    style: TextStyle(color: Colors.deepPurple),
                    underline: Container(
                      height: 2,
                      color: Colors.blue[300],
                    ),
                    onChanged: (Color newValue) {
                      setState(() {
                        dropdownValue = newValue;
                      });
                    },
                    items: recentUsedColors
                        .map<DropdownMenuItem<Color>>((Color value) {
                      return DropdownMenuItem<Color>(
                        value: value,
                        child: Container(height: 20, width: 20, color: value),
                      );
                    }).toList(),
                  ),

完整代码

import 'package:flutter/material.dart';

import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:flutter_colorpicker/material_picker.dart';
import 'package:flutter_colorpicker/block_picker.dart';
import 'package:flutter_colorpicker/utils.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Color currentColor = Colors.amber;

  List<Color> recentUsedColors = [];
  Color dropdownValue;

  void changeColor(Color color) {

    setState(() {
      currentColor = color;
      recentUsedColors.add(color);
    });

  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Color Picker Example'),
          bottom: TabBar(
            tabs: <Widget>[
              const Tab(text: 'HSV'),
              const Tab(text: 'Material'),
              const Tab(text: 'Block'),
            ],
          ),
        ),
        body: TabBarView(
          physics: const NeverScrollableScrollPhysics(),
          children: <Widget>[
            Center(
              child: Column(
                children: <Widget>[
                  DropdownButton<Color>(
                    //isDense: true,
                    hint: Text('Choose a goal category'),
                    value: dropdownValue,
                    icon: Icon(Icons.check_circle_outline),
                    iconSize: 24,
                    elevation: 16,
                    style: TextStyle(color: Colors.deepPurple),
                    underline: Container(
                      height: 2,
                      color: Colors.blue[300],
                    ),
                    onChanged: (Color newValue) {
                      setState(() {
                        dropdownValue = newValue;
                      });
                    },
                    items: recentUsedColors
                        .map<DropdownMenuItem<Color>>((Color value) {
                      return DropdownMenuItem<Color>(
                        value: value,
                        child: Container(height: 20, width: 20, color: value),
                      );
                    }).toList(),
                  ),
                  RaisedButton(
                    elevation: 3.0,
                    onPressed: () {
                      showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            titlePadding: const EdgeInsets.all(0.0),
                            contentPadding: const EdgeInsets.all(0.0),
                            content: SingleChildScrollView(
                              child: ColorPicker(
                                pickerColor: currentColor,
                                onColorChanged: changeColor,
                                colorPickerWidth: 300.0,
                                pickerAreaHeightPercent: 0.7,
                                enableAlpha: true,
                                displayThumbColor: true,
                                enableLabel: true,
                                paletteType: PaletteType.hsv,
                                pickerAreaBorderRadius: const BorderRadius.only(
                                  topLeft: const Radius.circular(2.0),
                                  topRight: const Radius.circular(2.0),
                                ),
                              ),
                            ),
                          );
                        },
                      );
                    },
                    child: const Text('Change me'),
                    color: currentColor,
                    textColor: useWhiteForeground(currentColor)
                        ? const Color(0xffffffff)
                        : const Color(0xff000000),
                  ),
                ],
              ),
            ),
            Center(
              child: RaisedButton(
                elevation: 3.0,
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        titlePadding: const EdgeInsets.all(0.0),
                        contentPadding: const EdgeInsets.all(0.0),
                        content: SingleChildScrollView(
                          child: MaterialPicker(
                            pickerColor: currentColor,
                            onColorChanged: changeColor,
                            enableLabel: true,
                          ),
                        ),
                      );
                    },
                  );
                },
                child: const Text('Change me'),
                color: currentColor,
                textColor: useWhiteForeground(currentColor)
                    ? const Color(0xffffffff)
                    : const Color(0xff000000),
              ),
            ),
            Center(
              child: RaisedButton(
                elevation: 3.0,
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('Select a color'),
                        content: SingleChildScrollView(
                          child: BlockPicker(
                            pickerColor: currentColor,
                            onColorChanged: changeColor,
                          ),
                        ),
                      );
                    },
                  );
                },
                child: const Text('Change me'),
                color: currentColor,
                textColor: useWhiteForeground(currentColor)
                    ? const Color(0xffffffff)
                    : const Color(0xff000000),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

工作演示

在此处输入图像描述

暂无
暂无

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

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