import 'package:flutter/material.dart';
class FruitSelector extends StatefulWidget {
@override
State<FruitSelector> createState() => _FruitSelectorState();
}
class _FruitSelectorState extends State<FruitSelector> {
String selectedFruit = 'Apple';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Fruit Selector')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButton<String>(
value: selectedFruit,
items: const [
DropdownMenuItem(value: 'Apple', child: Text('Apple')),
DropdownMenuItem(value: 'Banana', child: Text('Banana')),
DropdownMenuItem(value: 'Cherry', child: Text('Cherry')),
DropdownMenuItem(value: 'Date', child: Text('Date')),
],
onChanged: (String? newValue) {
if (newValue != null) {
setState(() {
selectedFruit = newValue;
});
}
},
),
const SizedBox(height: 20),
Text('Your choice: $selectedFruit', style: const TextStyle(fontSize: 18)),
],
),
),
);
}
}
We use a DropdownButton widget with a list of DropdownMenuItem for each fruit. The value property is set to the currently selected fruit. When the user picks a new fruit, the onChanged callback updates the selectedFruit state using setState, which triggers the UI to refresh and show the new choice below the dropdown.
This simple pattern lets users pick from a list and see their selection immediately.