首页 > 解决方案 > Flutter Textfield 从选项列表中选择

问题描述

我的 Flutter 应用程序中有一个消息组件。当用户发送新消息时,我希望用户只能从选项列表中选择收件人(即他们只能发送给有效的用户名)。

视图看起来像这样

                   TextField(
                      cursorColor: etenRed,
                      controller: recipient,
                      decoration: InputDecoration(
                        hintText: 'To: Username',
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                            color: etenRed,
                          ),
                        ),
                      ),
                      onChanged: (text) {
                        model.onSearchChanged(text);
                      },
                    ),
                    model.isSearchingForUsers
                        ? SizedBox(
                            height: 150,
                            child: ListView.separated(
                                separatorBuilder: (context, index) {
                                  return Divider(
                                    thickness: 0.5,
                                    color: Colors.black54,
                                  );
                                },
                                scrollDirection: Axis.vertical,
                                shrinkWrap: true,
                                itemCount: model.snapshots.length,
                                itemBuilder: (context, index) {
                                  return ListTile(
                                    onTap: () {
                                      recipient.text = model
                                          .snapshots[index].data['username'];
                                      model.resetList();
                                    },
                                    title: Text(model
                                        .snapshots[index].data['username']),
                                  );
                                }),
                          )
                        : Container(),

如何确保用户无法输入不存在的用户名?

标签: flutterdart

解决方案


尝试这样的事情:


if(usernames.contains(model.search)) {
  sendMessage();
}

usernames是用户名列表,model.search 是用户输入的用户名


推荐阅读