如何在flutter中获取下拉按钮的选定索引

siv*_*mar 11 dart flutter

如何获得选择下拉的下拉列表,

在dropdown按钮中没有获取选定索引的属性,如果有如何获取所选索引,我的代码如下所示:

new DropdownButton( hint:new Text("Select a users"),value: selectedUser,

              onChanged: (String newValue) {
                setState(() {
                  selectedUser = newValue;
                });
              },
              items: userInfoToMap.map((ListOfUsers value) {
                return new DropdownMenuItem<String>(
                    value: value.name,
                    child:new Text(value.name,style: new TextStyle(color: Colors.black))
                );
              })
                  .toList(),
            ),

          ),),
Run Code Online (Sandbox Code Playgroud)

Col*_*son 25

您应该使用自定义模型对象(例如User)作为类型DropdownButton.

视频

import'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class User {
  const User(this.name);

  final String name;
}

class MyApp extends StatefulWidget {
  State createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  User selectedUser;
  List<User> users = <User>[const User('Foo'), const User('Bar')];

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Center(
          child: new DropdownButton<User>(
            hint: new Text("Select a user"),
            value: selectedUser,
            onChanged: (User newValue) {
              setState(() {
                selectedUser = newValue;
              });
            },
            items: users.map((User user) {
              return new DropdownMenuItem<User>(
                value: user,
                child: new Text(
                  user.name,
                  style: new TextStyle(color: Colors.black),
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我们如何设置初始值? (2认同)

Nic*_*ale 9

与Collin Jackson的答案类似,您可以简单地使用字符串列表并检查indexOf来设置值,这在某些情况下可能比使用User类更好。如果要设置初始值,请在定义时将_user设置为整数值。

int _user;
...

var users = <String>[
  'Bob',
  'Allie',
  'Jason',
];

return new DropdownButton<String>(
  hint: new Text('Pickup on every'),
  value: _user == null ? null : users[_user],
  items: users.map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      _user = users.indexOf(value);
    });
  },
);
Run Code Online (Sandbox Code Playgroud)

  • 我为知识体系做出了贡献,所以其他人可能会受益 (9认同)
  • 这行代码解决了我的问题'value:_user == null?null :用户[_user],'谢谢:)。 (2认同)
  • 当我们有多个具有相同字符串的值时,这可能不起作用。假设我们有 var users = &lt;String&gt;[ 'Bob', 'Bob Martins', 'Allie', 'Jason', 'Jason Derulo']; 该方法将会有问题 (2认同)