我是新手,并尝试构建一个简单的下拉列表。
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);
}
}
运行此代码时,出现错误
════════小部件库捕获到异常══════════════════════════════════ ═════════════════════ 构建SimpleScreen(脏,依赖项:[_ LocalizationsScope- [GlobalKey#dab9d],_ InheritedTheme],状态:_SimpleScreenState#90ea9)时引发了以下断言: 'package:flutter / src / material / dropdown.dart':失败的断言:620行pos 15:'item == null || items.isEmpty ||值== null || items.where(((DropdownMenuItem item)=> item.value == value).length == 1':不正确。
答案 0 :(得分:1)
您缺少每个menuItem中的值。
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);
}
}