Skip to content

Instantly share code, notes, and snippets.

@Roaa94
Last active December 30, 2021 11:58
Show Gist options
  • Save Roaa94/08ace6b8f73cff0216673dcf9def433d to your computer and use it in GitHub Desktop.
Save Roaa94/08ace6b8f73cff0216673dcf9def433d to your computer and use it in GitHub Desktop.
Dropdown Demo
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Starter',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: StarterPage(),
);
}
}
class StarterPage extends StatefulWidget {
@override
State<StarterPage> createState() => _StarterPageState();
}
class _StarterPageState extends State<StarterPage> {
Map<int, int?> dropdownValues = {};
final List<String> _list = [
'List Item 1',
'List Item 2',
'List Item 3',
'List Item 4',
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const ScrollPhysics(),
itemCount: _list.length,
itemBuilder: (_, parentListIndex) {
List<String> selectedItemValues = <String>[
'Dropdown Item 1',
'Dropdown Item 2',
'Dropdown Item 3',
'Dropdown Item 4',
];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
padding: const EdgeInsets.all(5.0),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
hint: const Text('Select Item'), // Shown when value is null
// ?? (selectedItemValues.isNotEmpty ? 0 : null) => this adds a default value if the value is null
value: dropdownValues[parentListIndex] ?? (selectedItemValues.isNotEmpty ? 0 : null),
items: List.generate(
selectedItemValues.length,
(i) => DropdownMenuItem<int>(
value: i,
child: Text(selectedItemValues[i]),
),
),
onChanged: (newDropdownValue) {
setState(() {
dropdownValues[parentListIndex] = newDropdownValue!;
print('dropdown: ${dropdownValues[parentListIndex]}');
});
},
),
),
),
],
);
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment