0

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?

My Car
  • 4,198
  • 5
  • 17
  • 50
FetFrumos
  • 5,388
  • 8
  • 60
  • 98
  • Have you tried https://pub.dev/documentation/dropdown_button2/latest/dropdown_button2/DropdownButton2/selectedItemBuilder.html – Rahul Feb 19 '23 at 22:21

1 Answers1

1

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});
}

Peter Koltai
  • 8,296
  • 2
  • 10
  • 20