应该只有一项具有 [DropdownButton] 的值:
Posted
技术标签:
【中文标题】应该只有一项具有 [DropdownButton] 的值:【英文标题】:There should be exactly one item with [DropdownButton]'s value: 【发布时间】:2020-11-10 00:27:37 【问题描述】:String selectedItem = 'Instalação Fibra';
DropdownButton<String>(
value: selectedItem,
onChanged: (value)
setState(()
selectedItem = value;
);
,
items: <String>['Instalação de TV', 'Instalação Rádio']
.map<DropdownMenuItem<String>>((String e)
return DropdownMenuItem<String>(
value: e,
child: Text(e),
);
).toList(),
)
这怎么可能是错的? 这不是编译。我尝试了几种方法,但都出现了同样的错误。
【问题讨论】:
【参考方案1】:您可以在下面复制粘贴运行完整代码selectedItem
'Instalação Fibra'
在<String>['Instalação de TV', 'Instalação Rádio']
中不存在
您可以使用List<String> items
并设置selectedItem = items[0]
代码sn-p
List<String> items = ['Instalação Fibra','Instalação de TV', 'Instalação Rádio'];
String selectedItem;
@override
void initState()
selectedItem = items[0];
super.initState();
工作演示
完整代码
import 'package:flutter/material.dart';
void main()
runApp(MyApp());
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
class MyHomePage extends StatefulWidget
MyHomePage(Key key, this.title) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
class _MyHomePageState extends State<MyHomePage>
List<String> items = ['Instalação Fibra','Instalação de TV', 'Instalação Rádio'];
String selectedItem;
@override
void initState()
selectedItem = items[0];
super.initState();
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: DropdownButton<String>(
value: selectedItem,
onChanged: (value)
setState(()
selectedItem = value;
);
,
items: items.map<DropdownMenuItem<String>>((String e)
return DropdownMenuItem<String>(
value: e,
child: Text(e),
);
).toList(),
),
);
【讨论】:
以上是关于应该只有一项具有 [DropdownButton] 的值:的主要内容,如果未能解决你的问题,请参考以下文章
Flutter GetBuilder Dependent DropDownButton - 即使值已被重置,也应该只有一项具有 [DropdownButton] 的值
Flutter DropdownButton 颜色与父 Widgets 相同