DolDurma
DolDurma

Reputation: 17303

Flutter making DropDown widget with passing any structured data

In this new widget i want to make new DropDown in flutter with passing any structured data, for example in that extendedClass is a pairValue class which i want to pass it here.

this code is not correct and i can't pass that correctly there

class CDropDown extends StatelessWidget {
  final List<T> dataClass;
  final T className;
  CDropDown({@required this.className, @required this.dataClass});

  @override
  Widget build(BuildContext context) {
    return DropdownButton<className>(
      value: dataClass[0],
      underline: Container(),
      isExpanded: true,
      icon: Icon(Icons.keyboard_arrow_down),
      items: dataClass.map((className user) {
        return  DropdownMenuItem<className>(
          value: user,
          child:  Text(
            user.name),
          );
      }).toList(),
      onChanged: null,
    );
  }
}

for example:

class User {
  const User(this.id,this.name);

  final String name;
  final int id;
}
List<User> users = <User>[const User(1,'Foo'), const User(2,'Bar')];
CDropDown(className:User, dataClass :users );

Upvotes: 0

Views: 54

Answers (1)

Sam Chan
Sam Chan

Reputation: 1762

This is an suggestion

class CDropDown<T> extends StatelessWidget {
  final List<T> dataClass;
  final Widget Function(T) itemBuilder;
  CDropDown({@required this.dataClass, @required this.itemBuilder});

  @override
  Widget build(BuildContext context) {
    return DropdownButton<T>(
      value: dataClass[0],
      underline: Container(),
      isExpanded: true,
      icon: Icon(Icons.keyboard_arrow_down),
      items: dataClass.map((T user) {
        return DropdownMenuItem<T>(
          value: user,
          child: itemBuilder(user),
        );
      }).toList(),
      onChanged: null,
    );
  }
}

I add itemBuilder, the reason is that when I call user.name in CDropDown, it will show The getter 'name' isn't defined for the type 'T'.. And it should use like

class User {
  const User(this.id,this.name);

  final String name;
  final int id;
}
List<User> users = <User>[const User(1,'Foo'), const User(2,'Bar')];
CDropDown<User>(dataClass :users, itemBuilder:(user){return Text(user.name);} );

Upvotes: 1

Related Questions