Flutter自动建议TextField

时间:2018-09-22 07:48:12

标签: forms autocomplete flutter textfield

我正在开发Flutter应用,该应用在TextFormField内包含一个TextField / FormTextField之一将是自动建议/完成。

TextField输入更改时,什么是合适的窗口小部件来显示数据列表?

1 个答案:

答案 0 :(得分:0)

Flutter即将推出AutoComplete功能,您可以在此thread中跟踪其进度。除了在注释中使用提到的包之外,还可以在等待RawAutocomplete功能发布的同时,尝试将AutoComplete用于Text [Form]字段。您需要使用master channel才能尝试此操作。

下面是此demo之后的示例。

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var _textFieldHints = List<String>();
  var _textFieldController;

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

  _addAutoFillText() {
    if (_textFieldController.text.isEmpty) {
      // Don't add input text if TextFormField is empty
      debugPrint('_textFieldController.text is empty');
    } else {
      debugPrint('${_textFieldController.text} added');
      setState(() {
        // Add TextFormField String to List
        _textFieldHints.add(_textFieldController.text);
        // Clear TextFormField after adding
        _textFieldController.clear();
      });
      debugPrint('_textFieldHints contains:');
      _textFieldHints.sort();
      _textFieldHints.forEach((text) {
        debugPrint('$text');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          padding: EdgeInsets.all(16.0),
          child: RawAutocomplete<String>(
            optionsBuilder: (TextEditingValue textEditingValue) {
              if (textEditingValue.text == null ||
                  textEditingValue.text == '') {
                return const Iterable<String>.empty();
              }
              return _textFieldHints.where((String option) {
                return option
                    .toLowerCase()
                    .contains(textEditingValue.text.toLowerCase());
              });
            },
            onSelected: (String selection) {
              debugPrint('$selection selected');
            },
            fieldViewBuilder: (BuildContext context,
                TextEditingController textEditingController,
                FocusNode focusNode,
                VoidCallback onFieldSubmitted) {
              _textFieldController = textEditingController;
              return TextFormField(
                controller: _textFieldController,
                focusNode: focusNode,
                onFieldSubmitted: (String value) {
                  onFieldSubmitted();
                },
              );
            },
            optionsViewBuilder: (BuildContext context,
                AutocompleteOnSelected<String> onSelected,
                Iterable<String> options) {
              return Align(
                alignment: Alignment.topLeft,
                child: Material(
                  elevation: 4.0,
                  child: Container(
                    height: 200.0,
                    child: ListView.builder(
                      padding: EdgeInsets.all(8.0),
                      itemCount: options.length + 1,
                      itemBuilder: (BuildContext context, int index) {
                        if (index >= options.length) {
                          return TextButton(
                            child: const Text('clear'),
                            onPressed: () {
                              _textFieldController.clear();
                            },
                          );
                        }
                        final String option = options.elementAt(index);
                        return GestureDetector(
                          onTap: () {
                            onSelected(option);
                          },
                          child: ListTile(
                            title: Text(option),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _addAutoFillText(),
        child: Icon(Icons.add),
      ),
    );
  }
}

Demo