gpt4 book ai didi

当类用作值而不是字符串时, flutter 下拉失败

转载 作者:行者123 更新时间:2023-12-03 03:58:26 26 4
gpt4 key购买 nike

我有以下代码。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SimpleScreen());
}
}

class SimpleScreen extends StatefulWidget {
@override
_SimpleScreenState createState() => _SimpleScreenState();
}

class _SimpleScreenState extends State<SimpleScreen> {
ItemCls currentValue = ItemCls(name: 'one', price: 1);

List<DropdownMenuItem> _menuItems = <DropdownMenuItem>[
DropdownMenuItem(
child: new Container(
child: new Text("Item#1"),
width: 200.0,
),
value: ItemCls(name: 'one', price: 1)),
DropdownMenuItem(
child: new Container(
child: new Text("Item#2"),
width: 200.0,
),
value: ItemCls(name: 'two', price: 2))
];

@override
Widget build(BuildContext context) {
return new Scaffold(
body: Center(
child: DropdownButton(
value: currentValue,
items: _menuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
),
));
}

void onChanged(value) {
setState(() {
currentValue = value;
});
// print(value);
}
}

class ItemCls {
final String name;
final double price;

const ItemCls({
@required this.name,
@required this.price,
}) : assert(name != null),
assert(price != null);
}

失败了

The following assertion was thrown building SimpleScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#b1ff3], _InheritedTheme], state: _SimpleScreenState#d473f): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 620 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.

最佳答案

每个 DropDownMenuItem 中的 value 都必须是唯一的。 Dart 通过两种方式确保唯一性:定义 == 运算符和在对象上调用 hashCode。您需要将两者都添加到 ItemCls 类中:

class ItemCls {
final String name;
final double price;

const ItemCls({
@required this.name,
@required this.price,
}) : assert(name != null),
assert(price != null);

bool operator ==(dynamic other) {
return other is ItemCls &&
this.name == other.name &&
this.price == other.price;
}

@override
int get hashCode {
// Hash code algorithm derived from https://www.sitepoint.com/how-to-implement-javas-hashcode-correctly/
int hashCode = 1;
hashCode = (23 * hashCode) + this.name.hashCode;
hashCode = (23 * hashCode) + this.price.hashCode;
return hashCode;
}
}

关于当类用作值而不是字符串时, flutter 下拉失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com