我是 flutter 新手,正在尝试构建一个简单的下拉列表。
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> {
String currentValue = 'Item#1';
List<DropdownMenuItem> _menuItems = <DropdownMenuItem>[
DropdownMenuItem(child: new Container(
child: new Text ("Item#1"),
width: 200.0,
)
)
,
DropdownMenuItem(child: new Container(
child: new Text ("Item#2"),
width: 200.0, //200.0 to 100.0
)
)
];
@override
Widget build(BuildContext context) {
return new Scaffold(body:
DropdownButton(
value: currentValue,
items: _menuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
)
);
}
void onChanged(value) {
print(value);
}
}
当我运行此代码时,出现错误
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ The following assertion was thrown building SimpleScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#dab9d], _InheritedTheme], state: _SimpleScreenState#90ea9): '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.
最佳答案
您缺少每个菜单项中的值。
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> {
String currentValue = 'Item#1';
List<DropdownMenuItem> _menuItems = <DropdownMenuItem>[
DropdownMenuItem(
child: new Container(
child: new Text("Item#1"),
width: 200.0,
),
value: "Item#1"),
DropdownMenuItem(
child: new Container(
child: new Text("Item#2"),
width: 200.0, //200.0 to 100.0
),
value: "Item#2")
];
@override
Widget build(BuildContext context) {
return new Scaffold(
body: DropdownButton(
value: currentValue,
items: _menuItems,
onChanged: onChanged,
style: Theme.of(context).textTheme.title,
));
}
void onChanged(value) {
print(value);
}
}
关于 flutter 下拉失败断言行 620,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59206413/