I have the following code which I’ve modified.
import 'package:flutter/material.dart';
/// Flutter code sample for [DropdownButton].
void main() => runApp(const DropdownButtonApp());
class DropdownButtonApp extends StatelessWidget {
const DropdownButtonApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('DropdownButton Sample')),
body: const Center(
child: DropdownButtonExample(),
),
),
);
}
}
class DropdownButtonExample extends StatefulWidget {
const DropdownButtonExample({super.key});
@override
State<DropdownButtonExample> createState() => _DropdownButtonExampleState();
}
class _DropdownButtonExampleState extends State<DropdownButtonExample> {
List<DropdownMenuItem<String>> dropdownItems = [];
void addDropdownItem() {
dropdownItems.add(DropdownMenuItem<String>(
value: 'Hi',
child: Text('Hi'),
));
}
@override
Widget build(BuildContext context) {
Future.delayed(const Duration(seconds: 2), () {
addDropdownItem();
setState(() {
});
});
return DropdownButton<String>(
onChanged: (String? value) {},
items: dropdownItems,
);
}
}
Basically there’s a dropdown menu and every 2 seconds I add a new item to the list to simulate arrival of new information. And then the widget is rebuilt. If the menu is closed, then the items are then visible the next time it’s opened. But if the menu is already opened, the items will be added to the list but the dropdown menu won’t be updated to include these newly added items. How can I update the dropdown menu even if it’s opened while items are being added and the widget is rebuilding?
It looks like this:
1