[英]There should be exactly one item with [DropdownButton]'s
我想我想要一個這么簡單的東西,flutter 告訴我只有一個 item 或者沒有 item。 但我確信有不止一個項目,IDK,我應該如何針對這個問題提出問題。 我只想列出一個列表並使用 CustomClass 的項目制作一個下拉菜單。我確實從https://api.flutter.dev/flutter/material/DropdownButton-class.html復制粘貼,但當我用我的更改數據時。 ...
import 'package:flutter/material.dart';
class BreedJson {
final String breed;
final String img;
BreedJson(this.breed, this.img);
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String dropdownValue = 'default ';
final List<BreedJson> myBreedJson = [
BreedJson("Cavalier King Charles Spaniel",
'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'),
BreedJson('Curly-Coated Retriever',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSLqpKzfZ6L0TSvUKBhXwJQOnqfWzoaQWoIjCZu1s0evNhfSFWeNVMYWJYt0MqInbznRgE&usqp=CAU')
];
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: myBreedJson
.map<DropdownMenuItem<String>>((BreedJson value) => DropdownMenuItem<String>(
value: value.breed,
child: Text(value.img),
))
.toList());
}
}
myBreedJson
列表不包含default
,這就是它引發此錯誤的原因。
您可以最初傳遞 null 值,為此使dropdownValue
可以為空
String? dropdownValue;
嘗試這個:
String dropdownValue = "Cavalier King Charles Spaniel";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.