I using this model for my DropdownButtonFormField:
class MyItem {
final String fullName;
final String shortName;
}
This my UI code:
List<DropdownMenuItem<MyItem>> _getItems() {
return widget.items
.map((e) => DropdownMenuItem(
value: e,
child: Container(
color: AppColors.inputBackgroundColor,
alignment: Alignment.centerLeft,
child: Text(
'${e.fullName} (${e.shortName})',
style: AppStyles.bodyText1,
),
),
))
.toList();
}
DropdownButtonFormField2<MyItem>(
items: _getItems(),
),
I need to display "fullName + (shortName)" in the popup(items), and only the "shortName" in the input field itself (when I selected the value).
Is this possible?
Try to use selectedItemBuilder
:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
class MyWidget extends StatelessWidget {
final items = const [
MyItem(shortName: 'shortName1', fullName: 'Long Name 1'),
MyItem(shortName: 'shortName2', fullName: 'Long Name 2'),
MyItem(shortName: 'shortName3', fullName: 'Long Name 3')
];
@override
Widget build(BuildContext context) => DropdownButtonFormField<MyItem>(
selectedItemBuilder: (context) =>
items.map((e) => Text(e.shortName)).toList(),
items: _getItems(),
onChanged: (item) {});
List<DropdownMenuItem<MyItem>> _getItems() => items
.map((e) => DropdownMenuItem(
value: e,
child: Container(
alignment: Alignment.centerLeft,
child: Text(
'${e.fullName} (${e.shortName})',
),
),
))
.toList();
}
class MyItem {
final String fullName;
final String shortName;
const MyItem({required this.fullName, required this.shortName});
}