Как установить значение в AutoCompleteTextField? - PullRequest
0 голосов
/ 03 декабря 2018

У меня textfield, который отображает подсказки автозаполнения в качестве пользовательских типов, используя пакет autocomplete_textfield.Теперь я хочу отобразить выбранное предложение в textfield, для которого внутри метода itemSubmitted() я использую setState() { currentText = item.<suggestedText>}, который правильно печатает значение в консоли, но я не уверен, как отобразить это значение обратно в textfield.Если я не ошибаюсь, мне нужно использовать TextEditingController, чтобы получить и установить значение в textfield, но не уверен, как мне использовать TextEditingController внутри AutoCompleteTextField.

Текущий код ниже:

@override
  void initState() {
    _loadData();
    textField = AutoCompleteTextField<Categories>(
      style: new TextStyle(color: Colors.white, fontSize: 16.0),
        decoration: new InputDecoration(
            suffixIcon: Container(
              width: 85.0,
              height: 60.0,
              color: Colors.green,
              child: new IconButton(
                icon: new Image.asset(
                  'assets/search_icon_ivory.png',
                  color: Colors.white,
                  height: 18.0,
                ),
                onPressed: () {},
              ),
            ),
            fillColor: Colors.black,
            contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
            filled: true,
            hintText: 'Search',
            hintStyle: TextStyle(color: Colors.white)),
        itemSubmitted: (item) {
          setState(() {
            currentText = item.autocompleteterm;
            print(currentText);
          });
        },
        submitOnSuggestionTap: true,
        clearOnSubmit: true,
        textChanged: (item) {
        },
        key: key,
        suggestions: CategoryViewModel.categories,
        textInputAction: TextInputAction.go,
        itemBuilder: (context, item) {
          return new Container(
            color: Colors.black87,
            child: Padding(
              padding: EdgeInsets.all(8.0),
              child: new Text(item.autocompleteterm,
              style: TextStyle(
                color: Colors.white70,
                fontSize: 16.0
              )),
            ),
          );
        },
        itemSorter: (a, b) {
          return a.autocompleteterm.compareTo(b.autocompleteterm);
        },
        itemFilter: (item, query) {
          return item.autocompleteterm
              .toLowerCase()
              .startsWith(query.toLowerCase());
        },
        );
    super.initState();
    _getUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Color(0xFF13212C),
        appBar: AppBar(
          title: Text('Demo'),
        ),
        drawer: appDrawer(),
        body: new Center(
            child: new Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
              new Column(children: <Widget>[
                textField,
              ]),

1 Ответ

0 голосов
/ 05 декабря 2018

Это может быть достигнуто следующим образом:

itemSubmitted: (item) {
          setState(() => textField.textField.controller.text = item.autocompleteterm);
          },

И сделать clearOnSubmit: false, чтобы иметь возможность отображать выбранное значение в текстовом поле.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...