I want to make a simple DropDownButton
in Flutter. And I don't understand the error I'm getting:
And here is the code of the page with the error:
class MyPage extends StatefulWidget {
MyPage({super.key});
@override
State<MyPage> createState() => _Example();
}
class _Example extends State<MyPage> {
List<String> items = ['small', 'medium', 'large', 'extra-large'];
String? selectedItem = 'samll';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HDBOOKS'),
),
body: DropdownButton(
value: selectedItem,
items: items
.map((e) => DropdownMenuItem(value: e, child: Text(e)))
.toList(),
onChanged: (item) => setState(() {
selectedItem = item!;
}),
));
}
}
You have a typo in line String? selectedItem = **'samll'**;
that is not matching with the available options.
Below is the code working now with some improvements
import "package:flutter/material.dart";
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyPage(),
);
}
}
class MyPage extends StatefulWidget {
MyPage({super.key});
@override
State<MyPage> createState() => _Example();
}
class _Example extends State<MyPage> {
List<String> items = ['small', 'medium', 'large', 'extra-large'];
String? selectedItem = 'small';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HDBOOKS'),
),
body: DropdownButton<String>(
value: selectedItem,
items: items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: TextStyle(fontSize: 30),
),
);
}).toList(),
onChanged: (String? newValue) => setState(() {
selectedItem = newValue!;
}),
));
}
}