1.介绍

Widget 主要用于输入文本时,自动匹配相关内容并进行提示,点击提示后自动填充到输入框中

图片[1]专注Flutter相关技术及工具RawAutocomplete-提示输入框专注Flutter相关技术及工具Flutter经验之谈
效果图

2.如何使用?

  • 参数解释
参数类型参数介绍
AutocompleteOptionsViewBuilderoptionsViewBuilder构建选项框视图
AutocompleteOptionToStringdisplayStringForOption默认是(T)t.toString() , 取T的其中一个字段显示
AutocompleteOptionsBuilderoptionsBuilder查找符合的提示选项
AutocompleteFieldViewBuilder?fieldViewBuilder构建输入框视图
FocusNode?focusNode控制输入框焦点
AutocompleteOnSelected?onSelected当选中选项时,会调用
  • 简单使用
  1. 添加一个选项列表
  List<String> options = [
    'int',
    'double',
    'String',
    'num',
    'void',
    'extends',
    'class',
    'Widget',
    'StatefulWidget',
    'StatelessWidget',
    'abstract',
    'BuildContext',
  ];

2. 构建选项视图

  Widget _buildOptionsViews(
    BuildContext context,
    AutocompleteOnSelected<String> onSelected,
    Iterable<String> options,
  ) {
    return Align(
      alignment: Alignment.topLeft,
      child: Material(
        elevation: 0.0,
        child: Container(
          color: Theme.of(context).cardColor,
          constraints: BoxConstraints(maxHeight: 360),
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              String text = options.elementAt(index);
              return ListTile(
                onTap: () {
                  onSelected.call(text);
                },
                title: Text(text),
              );
            },
            itemCount: options.length,
          ),
        ),
      ),
    );
  }

3. 获取匹配到的选项

  Iterable<String> _buildOptions(TextEditingValue textEditingValue) {
    if (textEditingValue.text.isEmpty) return [];
    String text = textEditingValue.text;
    if (text.contains(' ')) {
      text = text.split(' ').last;
    }
    return options
        .where((element) =>
            RegExp('(.*)$text(.*)', caseSensitive: false).hasMatch(element))
        .toList();
  }

4. 构建输入框

  Widget _buildInputField(
      BuildContext context,
      TextEditingController textEditingController,
      FocusNode focusNode,
      VoidCallback onFieldSubmitted) {
    return TextFormField(
      controller: textEditingController,
      focusNode: focusNode,
      onFieldSubmitted: (String value) {
        onFieldSubmitted();
      },
    );
  }

5. 结合在一起

    RawAutocomplete<String>(
        onSelected: (s) {
          print('$s');
        },
        optionsViewBuilder: _buildOptionsViews,
        optionsBuilder: _buildOptions,
        fieldViewBuilder: _buildInputField,
      )

完成!

评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片