0
votes

Basically what I'm trying to do is to supply an initial value (grey) to a text field and once the user clicks the text field, the initial value is automatically cleared and the user input should be black. Currently my code is like this.

TextEditingController _controller;
FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: 'Search');
    _focusNode = FocusNode()..addListener(_onFocus);
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _controller.dispose();
    super.dispose();
  }

  void _onFocus() {
    if (_focusNode.hasFocus) _controller.clear();
  }

  Widget _buildSearchBox() {
    return CupertinoTextField(
      controller: _controller,
      focusNode: _focusNode,
      style: TextStyle(
          fontSize: 17,
          color: _focusNode.hasFocus
              ? CupertinoColors.black
              : CupertinoColors.systemGrey,
      ),
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
      ),
    );
  }

I know it doesn't work because: (a) everytime the user types something, does something else and clicks the text field again, his input is cleared (b) I hope only the initial value is grey, but once the user does something else, his input also becomes grey.

Can anyone help me with it? Thanks.

2
Can't you just use a hint for this? You can style it differently from the input text and it basically is the thing you want. - Thepeanut

2 Answers

1
votes

Add a placeholder field see you cannot style it, individually as

It is a lighter colored placeholder hint that appears on the first line of the text field when the text entry is empty. Defaults to having no placeholder text.The text style of the placeholder text matches that of the text field's main text entry except a lighter font weight and a grey font color.

CupertinoTextField(
  placeholder: "Enter Email",   //Add this and your work is done
  controller: _controller,
  focusNode: _focusNode,
  style: TextStyle(
      fontSize: 17,
      color: _focusNode.hasFocus
          ? CupertinoColors.black
          : CupertinoColors.systemGrey,
  ),
  decoration: BoxDecoration(
    color: CupertinoColors.systemGrey6,
  ),
);
1
votes

From what I understood from the question, one way you can do this is something like this

  FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode()..addListener(_onFocus);
  }

  void _onFocus() {
    setState((){});
  }

  Widget _buildSearchBox() {
    return CupertinoTextField(
      placeholder: "Search",
      focusNode: _focusNode,
      style: TextStyle(
        fontSize: 17,
        color: _focusNode.hasFocus
            ? CupertinoColors.black
            : CupertinoColors.systemGrey,
      ),
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
      ),
    );
  }

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