带有IconButton的Flutter TextField

时间:2019-05-23 12:07:50

标签: flutter

此小部件有两个问题。添加suffix: IconButton...时,它将在文本字段中添加看起来像填充的内容。以及_searchController.text不为空时如何显示后缀图标。我尝试了_searchController.text != null ? IconButton(...): 'not sure what to return here'

  Widget _searchBox() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        labelText: "Search",
        hintText: "Search",
        prefixIcon: Icon(Icons.search),
        suffix: IconButton(
          icon: Icon(Icons.clear),
          onPressed: () => _searchController.clear(),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
        ),
      ),
    );
  }

后缀:

enter image description here

没有后缀:

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试:

Widget _searchBox() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        labelText: "Search",
        hintText: "Search",
        prefixIcon: Icon(Icons.search,color: Colors.white,),

        suffix: InkWell(

          child: Icon(Icons.clear),
          onPressed: () => _searchController.clear(),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(10.0),
          ),
        ),
      ),
    );
  }

答案 1 :(得分:1)

请改用suffixIcon。要根据状态更新图标,您需要在某处调用setState。

尝试一下:

import 'package:flutter/material.dart';

class SearchWidget extends StatefulWidget {


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

class _SearchWidgetState extends State<SearchWidget> {
  String _searchText = "";
  TextEditingController _searchController;
  @override
  Widget build(BuildContext context) {
      return TextField(
        controller: _searchController,
        decoration: InputDecoration(
          labelText: "Search",
          hintText: "Search",
          prefixIcon: Icon(Icons.search,color: Colors.white,),

          suffixIcon: _searchText.isNotEmpty ? IconButton(icon: Icon(Icons.clear),onPressed: () {
            setState(() {
              _searchController.clear();
            });},) : null,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
          ),
        ),
      );
    }

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _searchController.addListener(() {
      setState(() {
        _searchText = _searchController.text;
      });
    });
  }

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

编辑:别忘了处置

答案 2 :(得分:1)

我最终使用了两个答案中的想法。一个没有解释如何显示和隐藏图标,而另一个似乎太复杂了。我只做www.example.com/product

_searchController.text.isEmpty