Flutter原始自动完成建议被软键盘遮挡

6

我正在创建一个原始的自动完成小部件。

问题是,如果小部件位于屏幕中心或底部附近,当我开始输入时,自动建议显示会被软键盘遮挡。如何构建optionsViewBuilder以克服选项在键盘下被隐藏的情况?

示例源代码:

class AutoCompleteWidget extends StatefulWidget {

  const AutoCompleteWidget(
    Key key,
  ) : super(key: key);

  @override
  _AutoCompleteWidgetState createState() => _AutoCompleteWidgetState();
}

class _AutoCompleteWidgetState extends State<AutoCompleteWidget> {
  late TextEditingController _textEditingController;
  String? _errorText;
  final FocusNode _focusNode = FocusNode();
  final GlobalKey _autocompleteKey = GlobalKey();
  List<String> _autoSuggestions = ['abc', 'def', 'hij', 'aub', 'bted' 'donfr', 'xyz'];

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return RawAutocomplete<String>(
      key: _autocompleteKey,
      focusNode: _focusNode,
      textEditingController: _textEditingController,
      optionsBuilder: (TextEditingValue textEditingValue) {
        if (textEditingValue.text == '') {
          return _autoSuggestions;
        }
        return _autoSuggestions.where((dynamic option) {
          return option
              .toString()
              .toLowerCase()
              .startsWith(textEditingValue.text.toLowerCase());
        });
      },
      optionsViewBuilder: (BuildContext context,
          AutocompleteOnSelected<String> onSelected, Iterable<String> options) {
        return Material(
          elevation: 4.0,
          child: ListView(
            children: options
                .map((String option) => GestureDetector(
                      onTap: () {
                        onSelected(option);
                      },
                      child: ListTile(
                        title: Text(option),
                      ),
                    ))
                .toList(),
          ),
        );
      },
      fieldViewBuilder: (
        BuildContext context,
        TextEditingController textEditingController,
        FocusNode focusNode,
        VoidCallback onSubmitted,
      ) {
        return Card(
          elevation: (null == _errorText ? 8 : 0),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
          child: TextField(
            controller: textEditingController,
            focusNode: focusNode,
          ),
        );
      },
    );
  }
}

你有找到解决方法吗? - Rens
1
不,我已经转而使用下拉菜单/下拉搜索小部件了。 - Ashish Khurange
3个回答

3
我提出的解决方案是使用 TextFormField 构建自己版本的简单自动完成小部件,并在其上设置 scrollPadding。我在一个具有与该内边距匹配的设置高度的容器中显示结果。
  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        // THE AUTOCOMPLETE INPUT FIELD
        TextFormField(
          focusNode: _focusNode,
          scrollPadding: const EdgeInsets.only(bottom: 300),
          maxLines: null,
          key: const ValueKey('company_address'),
          autocorrect: false,
          enableSuggestions: false,
          controller: widget.textEditingController,
          validator: (value) {
            if (value!.isEmpty) {
              return _i10n.enterAName;
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: widget.labelText,
          ),
          textInputAction: TextInputAction.next,
          onChanged: (_) {
            _handleChange();
            widget.onChange();
          },
          onTap: () {
            setState(() {
              _showAutocompleteSuggestions = true;
            });
          },
        ),
        const SizedBox(
          height: 5.0,
        ),
        // THE AUTOCOMPLETE RESULTS
        if (_showAutocompleteSuggestions)
          Container(
            // height: _autocompleteHeight,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              boxShadow: const [
                BoxShadow(blurRadius: 10.0, color: Colors.black12)
              ],
              color: Colors.white,
            ),
            constraints: const BoxConstraints(maxHeight: 200.0),
            child: Scrollbar(
              child: SingleChildScrollView(
                child: Column(children: [
                  if (_autocompleteSuggestions.isEmpty)
                    const ListTile(
                      title: Text('No results'),
                    )
                  else
                    ..._autocompleteSuggestions.map((_autocompleteSuggestion) =>
                        Material(
                          child: InkWell(
                            onTap: () {
                              _handleSelectSuggestion(_autocompleteSuggestion);
                            },
                            child: ListTile(
                              leading: const Icon(Icons.location_on_outlined),
                              title: Text(_autocompleteSuggestion.description),
                            ),
                          ),
                        ))
                ]),
              ),
            ),
          ),
      ],
    );
  }

抱歉这段代码马上就放出来了。


0

您可以使用一些约束条件来实现您想要的行为。

首先,将根小部件作为 LayoutBuilder 的子级来获取布局约束(我还使用了 Align 顶部来更好地放置选项视图)。

之后,您可以将 ConstrainedBox 用作选项视图的父级。

您可以根据需要自定义这些约束。下面的示例设置为将屏幕高度的一半作为选项视图的最大高度减去底部视图插入量(状态为软键盘的状态)。

您在示例中给出的代码将类似于以下内容:

@override
Widget build(BuildContext context) {
  return Align(
    alignment: Alignment.topLeft,
    child: LayoutBuilder(
    builder: (context, constraints) => Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: 16,
      ),
      child: RawAutocomplete<String>(
        key: _autocompleteKey,
        focusNode: _focusNode,
        textEditingController: _textEditingController,
        optionsBuilder: (TextEditingValue textEditingValue) {
          if (textEditingValue.text == '') {
            return _autoSuggestions;
          }
          return _autoSuggestions.where((dynamic option) {
            return option
                .toString()
                .toLowerCase()
                .startsWith(textEditingValue.text.toLowerCase());
          });
        },
        optionsViewBuilder: (BuildContext context,
            AutocompleteOnSelected<String> onSelected,
            Iterable<String> options) {
          return Container(
            margin: EdgeInsets.symmetric(horizontal: 16),
            child: Material(
              elevation: 4.0,
              child: ConstrainedBox(
                constraints: BoxConstraints(
                  maxWidth: constraints.biggest.width,
                  maxHeight: (MediaQuery.of(context).size.height / 2) -
                      (MediaQuery.of(context).viewInsets.bottom / 4),
                ),
                child: ListView(
                  children: options
                      .map((String option) => GestureDetector(
                            onTap: () {
                              onSelected(option);
                            },
                            child: ListTile(
                              title: Text(option),
                            ),
                          ))
                      .toList(),
                ),
              ),
            ),
          );
        },
        fieldViewBuilder: (
          BuildContext context,
          TextEditingController textEditingController,
          FocusNode focusNode,
          VoidCallback onSubmitted,
        ) {
          return Card(
            elevation: (null == _errorText ? 8 : 0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.0)),
            child: TextField(
              controller: textEditingController,
              focusNode: focusNode,
            ),
          );
        },
      ),
    ),
  ),
 );
}

-1

在具有 reverse: true 属性的 RawAutocomplete 中,您应该在屏幕上使用 SingleChildScrollView。

就像下面这样:

child: Center(
  child: SingleChildScrollView(
    reverse: true,
    child: Column()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接