如何在flutter中实现下拉列表?

时间:2018-03-14 08:46:54

标签: drop-down-menu dart flutter

我有一个我希望在Flutter中作为下拉列表实现的位置列表。我对这门语言很陌生。这就是我所做的。

new DropdownButton(
  value: _selectedLocation,
  onChanged: (String newValue) {
    setState(() {
      _selectedLocation = newValue;
     });
},
items: _locations.map((String location) {
  return new DropdownMenuItem<String>(
     child: new Text(location),
  );
}).toList(),

这是我的项目清单:

List<String> _locations = ['A', 'B', 'C', 'D'];

我收到以下错误。

Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 468 pos 15: 'value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.

我假设_selectedLocation的值为空。但我正在初始化它。

String _selectedLocation = 'Please choose a location';

18 个答案:

答案 0 :(得分:25)

试试这个

new DropdownButton<String>(
  items: <String>['A', 'B', 'C', 'D'].map((String value) {
    return new DropdownMenuItem<String>(
      value: value,
      child: new Text(value),
    );
  }).toList(),
  onChanged: (_) {},
)

答案 1 :(得分:7)

使用StatefulWidgetsetState更新下拉菜单。

  String _dropDownValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      hint: _dropDownValue == null
          ? Text('Dropdown')
          : Text(
              _dropDownValue,
              style: TextStyle(color: Colors.blue),
            ),
      isExpanded: true,
      iconSize: 30.0,
      style: TextStyle(color: Colors.blue),
      items: ['One', 'Two', 'Three'].map(
        (val) {
          return DropdownMenuItem<String>(
            value: val,
            child: Text(val),
          );
        },
      ).toList(),
      onChanged: (val) {
        setState(
          () {
            _dropDownValue = val;
          },
        );
      },
    );
  }

下拉菜单的初始状态:

Initial State

打开下拉菜单并选择值:

Select Value

将所选值反映到下拉列表中

Value selected

答案 2 :(得分:6)

首先,让我们研究错误的含义(我引用了Flutter 1.2引发的错误,但想法是相同的):

  

断言失败:560行pos 15:'item == null || items.isEmpty ||值== null || items.where(((DropdownMenuItem item)=> item.value == value).length == 1':不正确。

有四个or条件。必须至少满足其中之一:

    提供了
  • 项(DropdownMenuItem个小部件的列表)。这样就消除了items == null
  • 提供了非空列表。这样就消除了items.isEmpty
  • 还给出了一个值(_selectedLocation)。这消除了value == null。请注意,这是DropdownButton的值,而不是DropdownMenuItem的值。

因此只剩下最后一个检查。归结为:

  

遍历DropdownMenuItem。查找所有value等于_selectedLocation的东西。然后,检查找到多少与之匹配的项目。必须只有一个具有此值的小部件。否则,将引发错误。

代码显示的方式,没有DropdownMenuItem小部件的值为_selectedLocation。相反,所有小部件的值都设置为null。自null != _selectedLocation起,最后一个条件失败。通过将_selectedLocation设置为null进行验证-应用程序应运行。

要解决此问题,我们首先需要在每个DropdownMenuItem上设置一个值(以便可以将某些内容传递给onChanged回调):

return DropdownMenuItem(
    child: new Text(location),
    value: location,
);

该应用仍将失败。这是因为您的列表仍然不包含_selectedLocation的值。您可以通过两种方式使应用程序正常工作:

  • 选项1 。添加另一个具有该值的小部件(以满足items.where((DropdownMenuItem<T> item) => item.value == value).length == 1)。如果要让用户重新选择Please choose a location选项,可能会有用。
  • 选项2 。将某些内容传递给hint:参数,并将selectedLocation设置为null(以满足value == null的条件)。如果您不希望Please choose a location继续使用,则很有用。

请参见下面的代码,其中显示了操作方法:

import 'package:flutter/material.dart';

void main() {
  runApp(Example());
}

class Example extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
//  List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D']; // Option 1
//  String _selectedLocation = 'Please choose a location'; // Option 1
  List<String> _locations = ['A', 'B', 'C', 'D']; // Option 2
  String _selectedLocation; // Option 2

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: DropdownButton(
            hint: Text('Please choose a location'), // Not necessary for Option 1
            value: _selectedLocation,
            onChanged: (newValue) {
              setState(() {
                _selectedLocation = newValue;
              });
            },
            items: _locations.map((location) {
              return DropdownMenuItem(
                child: new Text(location),
                value: location,
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

答案 3 :(得分:5)

您需要在代码中添加value: location才能使用它。检查this

items: _locations.map((String location) {
  return new DropdownMenuItem<String>(
     child: new Text(location),
     value: location,
  );
}).toList(),

答案 4 :(得分:5)

你必须考虑到这一点(来自DropdownButton docs):

  

“项目必须具有不同的值,如果值不为null,则必须   在他们中间。“

所以基本上你有这个字符串列表

List<String> _locations = ['A', 'B', 'C', 'D'];

您在Dropdown值属性中的值初始化如下:

String _selectedLocation = 'Please choose a location';

试试这个清单:

List<String> _locations = ['Please choose a location', 'A', 'B', 'C', 'D'];

这应该有效:)

如果您不想添加类似的字符串(在列表上下文中),请查看“提示”属性,您可以使用以下内容:

DropdownButton<int>(
          items: locations.map((String val) {
                   return new DropdownMenuItem<String>(
                        value: val,
                        child: new Text(val),
                         );
                    }).toList(),
          hint: Text("Please choose a location"),
          onChanged: (newVal) {
                  _selectedLocation = newVal;
                  this.setState(() {});
                  });

答案 5 :(得分:3)

将值放在项目内,然后它将起作用

new DropdownButton<String>(
              items:_dropitems.map((String val){
                return DropdownMenuItem<String>(
                  value: val,
                  child: new Text(val),
                );
              }).toList(),
              hint:Text(_SelectdType),
              onChanged:(String val){
                _SelectdType= val;
                setState(() {});
                })

答案 6 :(得分:3)

制作您的自定义小部件:

import 'package:flutter/material.dart';

/// Usage:
/// CustomDropdown<String>(
//     items: ['A', 'B', 'C'],
//     onChanged: (val) => _selectedValue = val,
//     center: true,
//  ),
/// --> Remember: f.toString() at line 105 is @override String toString() in your class
// @override
// String toString() {
//   return name;
// }
class CustomDropdown<T> extends StatefulWidget {
  CustomDropdown({
    Key key,
    @required this.items,
    @required this.onChanged,
    this.onInit,
    this.padding = const EdgeInsets.only(top: 10.0),
    this.height = 40,
    this.center = false,
    this.itemText,
  }) : super(key: key);

  /// list item
  List<T> items;

  /// onChanged
  void Function(T value) onChanged;

  /// onInit
  void Function(T value) onInit;

  ///padding
  EdgeInsetsGeometry padding;

  /// container height
  double height;

  /// center
  bool center;

  String Function(String text) itemText;

  @override
  _CustomDropdownState<T> createState() => _CustomDropdownState();
}

class _CustomDropdownState<T> extends State<CustomDropdown<T>> {
  /// current selected value
  T _selectedValue;

  @override
  void initState() {
    super.initState();
    _initValue();
  }

  @override
  Widget build(BuildContext context) {
    return _buildBody();
  }

  /// set default selected value when init
  _initValue() {
    _selectedValue = widget.items[0];
    if (widget.onInit != null) widget.onInit(_selectedValue);
  }

  _buildBody() {
    Color borderLine = Color(0xffc0c0c0);
    return Padding(
      padding: widget.padding,
      child: Row(
        mainAxisAlignment: (widget.center)
            ? MainAxisAlignment.center
            : MainAxisAlignment.start,
        children: <Widget>[
          new Container(
            height: widget.height,
            padding: EdgeInsets.only(left: 10.0),
            decoration: ShapeDecoration(
              color: Colors.white,
              shape: RoundedRectangleBorder(
                side: BorderSide(
                    width: 0.8, style: BorderStyle.solid, color: borderLine),
                borderRadius: BorderRadius.all(Radius.circular(5.0)),
              ),
            ),
            child: new DropdownButtonHideUnderline(
              child: new DropdownButton<T>(
                value: _selectedValue,
                onChanged: (T newValue) {
                  setState(() {
                    _selectedValue = newValue;
                    widget.onChanged(newValue);
                  });
                },
                items: widget.items.map((T f) {
                  return new DropdownMenuItem<T>(
                    value: f,
                    child: new Text(
                      (widget.itemText != null)
                          ? widget.itemText(f.toString())
                          : f.toString(),
                      style: new TextStyle(color: Colors.black),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
  • 之后,简单的调用:

    CustomDropdown<String>(
          items: ['A', 'B', 'C'],
          onChanged: (val) => _selectedValue = val,
          center: true,
        )
    
  • 或者和你的班级一起:

    班级学生{ 内部标识; 字符串名称;

    A(this.id,this.name);

    //记住覆盖 @覆盖 字符串 toString() { 返回名称; } }

并调用:

CustomDropdown<Student>(
    items: studentList,
    onChanged: (val) => _selectedValue = val,
    center: true,
),

答案 7 :(得分:2)

您可以使用DropDownButton类来创建下拉列表:

...
...
String dropdownValue = 'One';
...
...
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: DropdownButton<String>(
      value: dropdownValue,
      onChanged: (String newValue) {
        setState(() {
          dropdownValue = newValue;
        });
      },
      items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    ),
  ),
);
...
...

请参阅此flutter web page

答案 8 :(得分:2)

如果您不希望Drop list像弹出窗口一样显示。您可以像我一样以这种方式自定义它(它会显示在同一平面上,请参见下图):

enter image description here

展开后:

enter image description here

请按照以下步骤操作: 首先,创建一个名为drop_list_model.dart的飞镖文件:

import 'package:flutter/material.dart';

class DropListModel {
  DropListModel(this.listOptionItems);

  final List<OptionItem> listOptionItems;
}

class OptionItem {
  final String id;
  final String title;

  OptionItem({@required this.id, @required this.title});
}

接下来,创建文件file select_drop_list.dart

import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';

class SelectDropList extends StatefulWidget {
  final OptionItem itemSelected;
  final DropListModel dropListModel;
  final Function(OptionItem optionItem) onOptionSelected;

  SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);

  @override
  _SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}

class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {

  OptionItem optionItemSelected;
  final DropListModel dropListModel;

  AnimationController expandController;
  Animation<double> animation;

  bool isShow = false;

  _SelectDropListState(this.optionItemSelected, this.dropListModel);

  @override
  void initState() {
    super.initState();
    expandController = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: 350)
    );
    animation = CurvedAnimation(
      parent: expandController,
      curve: Curves.fastOutSlowIn,
    );
    _runExpandCheck();
  }

  void _runExpandCheck() {
    if(isShow) {
      expandController.forward();
    } else {
      expandController.reverse();
    }
  }

  @override
  void dispose() {
    expandController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: const EdgeInsets.symmetric(
                horizontal: 15, vertical: 17),
            decoration: new BoxDecoration(
              borderRadius: BorderRadius.circular(20.0),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                    blurRadius: 10,
                    color: Colors.black26,
                    offset: Offset(0, 2))
              ],
            ),
            child: new Row(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Icon(Icons.card_travel, color: Color(0xFF307DF1),),
                SizedBox(width: 10,),
                Expanded(
                    child: GestureDetector(
                      onTap: () {
                        this.isShow = !this.isShow;
                        _runExpandCheck();
                        setState(() {

                        });
                      },
                      child: Text(optionItemSelected.title, style: TextStyle(
                          color: Color(0xFF307DF1),
                          fontSize: 16),),
                    )
                ),
                Align(
                  alignment: Alignment(1, 0),
                  child: Icon(
                    isShow ? Icons.arrow_drop_down : Icons.arrow_right,
                    color: Color(0xFF307DF1),
                    size: 15,
                  ),
                ),
              ],
            ),
          ),
          SizeTransition(
              axisAlignment: 1.0,
              sizeFactor: animation,
              child: Container(
                margin: const EdgeInsets.only(bottom: 10),
                  padding: const EdgeInsets.only(bottom: 10),
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                          blurRadius: 4,
                          color: Colors.black26,
                          offset: Offset(0, 4))
                    ],
                  ),
                  child: _buildDropListOptions(dropListModel.listOptionItems, context)
              )
          ),
//          Divider(color: Colors.grey.shade300, height: 1,)
        ],
      ),
    );
  }

  Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
    return Column(
      children: items.map((item) => _buildSubMenu(item, context)).toList(),
    );
  }

  Widget _buildSubMenu(OptionItem item, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
      child: GestureDetector(
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                padding: const EdgeInsets.only(top: 20),
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
                ),
                child: Text(item.title,
                    style: TextStyle(
                        color: Color(0xFF307DF1),
                        fontWeight: FontWeight.w400,
                        fontSize: 14),
                    maxLines: 3,
                    textAlign: TextAlign.start,
                    overflow: TextOverflow.ellipsis),
              ),
            ),
          ],
        ),
        onTap: () {
          this.optionItemSelected = item;
          isShow = false;
          expandController.reverse();
          widget.onOptionSelected(item);
        },
      ),
    );
  }

}

初始化值:

DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Chọn quyền truy cập");

最后使用它:

SelectDropList(
           this.optionItemSelected, 
           this.dropListModel, 
           (optionItem){
                 optionItemSelected = optionItem;
                    setState(() {
  
                    });
               },
            )

答案 9 :(得分:1)

对于有兴趣实施自定义DropDown的{​​{1}}的任何人,您都可以按照下面的步骤进行操作。

  1. 假设您有一个名为class的类,其中包含以下代码和一个Language方法,该方法返回一个static

    List<Language>
  2. 在任何要实现class Language { final int id; final String name; final String languageCode; Language(this.id, this.name, this.languageCode); static List<Language> getLanguages() { return <Language>[ Language(1, 'English', 'en'), Language(2, 'فارسی', 'fa'), Language(3, 'پشتو', 'ps'), ]; } } 的地方,都可以DropDown import类首先按照以下方式使用

    Language

答案 10 :(得分:0)

当我遇到想要一个不太通用的DropdownStringButton的问题时,我只是创建了它:

dropdown_string_button.dart

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddMvc(options =>
        {
            options.SslPort = int.Parse(Configuration.GetValue<string>("https_port"));
            options.Filters.Add(typeof(RequireHttpsAttribute));
            options.Filters.Add(typeof(JsonExceptionFilter));
        })
        .AddJsonOptions(p => p.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);


        services
            .AddDbContextPool<ShopDb>(opt =>
        {
            var cs = Configuration.GetValue<string>("connectionstrings:HomeAppliancesStore");
            opt.UseSqlServer(cs, p => p.MaxBatchSize(2));
            opt.ConfigureWarnings(p => p.Throw(RelationalEventId.QueryClientEvaluationWarning));

            opt.UseOpenIddict<Guid>();
        });

        services.AddIdentity<AppUser, AppRole>(opt =>
        {
            opt.Password.RequireUppercase = false;
            opt.Password.RequiredUniqueChars = 0;
            opt.Password.RequiredLength = 6;
            opt.Password.RequireNonAlphanumeric = false;

            opt.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            opt.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            opt.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        })
        .AddEntityFrameworkStores<ShopDb>()
        .AddDefaultTokenProviders();

        services.AddOpenIddict()
            .AddCore(p =>
            {
                p.UseEntityFrameworkCore()
                    .UseDbContext<ShopDb>()
                    .ReplaceDefaultEntities<Guid>();
            })
            .AddServer(opt =>
            {
                opt.UseMvc();

                opt.EnableTokenEndpoint("/token");
                opt.EnableLogoutEndpoint("/logout");

                opt.AllowPasswordFlow();
                opt.AllowRefreshTokenFlow();

                opt.AcceptAnonymousClients();

                opt.DisableHttpsRequirement(); // just for development

                opt.SetAccessTokenLifetime(TimeSpan.FromDays(1));
                opt.SetIdentityTokenLifetime(TimeSpan.FromDays(1));

            })
            .AddValidation();

        services.AddAuthentication(opt =>
        {
            opt.DefaultAuthenticateScheme = OpenIddictValidationDefaults.AuthenticationScheme;
            opt.DefaultScheme = OpenIddictValidationDefaults.AuthenticationScheme;
            opt.DefaultChallengeScheme = OpenIddictValidationDefaults.AuthenticationScheme;
        });

        services.AddAuthorization(opt =>
        {
            opt.AddPolicy(Constants.BossPolicy,
                p => p.RequireClaim(Constants.RoleClaimName, new List<string> { Constants.ManagerClaimValue }));
        });

       // Removed for brevity
    }

答案 11 :(得分:0)

当我用新的动态值替换默认值时,这发生在我身上。但是,您的代码可能会依赖于该默认值。因此,请尝试使用默认值保存在常量中的常量作为备用。

const defVal = 'abcd';
String dynVal = defVal;

// dropdown list whose value is dynVal that keeps changing with onchanged
// when rebuilding or setState((){})

dynVal = defVal;
// rebuilding here...

答案 12 :(得分:0)

更改

List<String> _locations = ['A', 'B', 'C', 'D'];

收件人

List<String> _locations = [_selectedLocation, 'A', 'B', 'C', 'D'];

_selectedLocation必须是您的商品列表的一部分;

答案 13 :(得分:0)

您收到的错误是由于要求一个空对象的属性。您的商品必须为null,因此在要求比较其价值时会遇到该错误。检查您要获取数据还是列表是对象列表,而不是简单的字符串。

答案 14 :(得分:0)

使用此代码。

-notmatch '^\s*$'

在主体中我们称为

sort -unique

答案 15 :(得分:0)

假设我们正在创建货币下拉列表:

List _currency = ["INR", "USD", "SGD", "EUR", "PND"];
List<DropdownMenuItem<String>> _dropDownMenuCurrencyItems;
String _currentCurrency;

List<DropdownMenuItem<String>> getDropDownMenuCurrencyItems() {
  List<DropdownMenuItem<String>> items = new List();
  for (String currency in _currency) {
    items.add(
      new DropdownMenuItem(value: currency, child: new Text(currency)));
  }
  return items;
}

void changedDropDownItem(String selectedCurrency) {
  setState(() {
    _currentCurrency = selectedCurrency;
  });
}

在正文部分添加以下代码:

new Row(children: <Widget>[
  new Text("Currency: "),
  new Container(
    padding: new EdgeInsets.all(16.0),
  ),
  new DropdownButton(
    value: _currentCurrency,
    items: _dropDownMenuCurrencyItems,
    onChanged: changedDropDownItem,
  )
])

答案 16 :(得分:0)

当我尝试在下拉列表中显示动态字符串列表时,我也遇到了DropDownButton的类似问题。我最终创建了一个插件:flutter_search_panel。不是下拉插件,但是您可以显示具有搜索功能的项目。

使用以下代码来使用小部件:

    FlutterSearchPanel(
        padding: EdgeInsets.all(10.0),
        selected: 'a',
        title: 'Demo Search Page',
        data: ['This', 'is', 'a', 'test', 'array'],
        icon: new Icon(Icons.label, color: Colors.black),
        color: Colors.white,
        textStyle: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
        onChanged: (value) {
          print(value);
        },
   ),

答案 17 :(得分:0)

这是我发现最有用的代码。 它为您提供所需的一切。 (ctrl+c , ctrl+v 会工作???)

Sub test()

    Dim s As String
    s = "3: CALL U(Base,EZSP,Nr1,Pr-nr=20,Offset=1,Path=2,WNr-Point=20,Pr=65,ON)"
    
    Dim Regex As Object, m As Object
    Set Regex = CreateObject("vbscript.regexp")
    With Regex
      .Global = True
      .MultiLine = False
      .IgnoreCase = True
      .pattern = "(W-Point|WR/KE-Point|WNr-Point|SST_P-Nr)( *= *)(\d*)"
    End With

    If Regex.test(s) Then
        Set m = Regex.Execute(s)(0).submatches
        Debug.Print m(0), "'" & m(1) & "'", m(2)
    End If
End Sub