1

I'm trying to move my TextFormField logic to flutter hooks so I have password field where I want implement obscure text. So on tap of button it should hide/unhide the text. Now I using setState() in the hooks to do that but it rebuilds the whole UI and moves focus to first field because I have set autoFocus for first field so How I can make sure the it rebuilds only that specific TextFormField.

My custom hooks file,

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


enum Index { email, password }

TextFormField useTextFormField(Index index) {
  return use(_CustomHook(index: index));
}

class _CustomHook extends Hook<TextFormField> {
  final Index index;

  _CustomHook({@required this.index});

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

class _CustomHookState extends HookState<TextFormField, _CustomHook> {
  Index index;
  bool obscure = false;
  @override
  TextFormField build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        hintText: 'some help',
        suffixIcon: IconButton(
          onPressed: () {
            setState(() {
              obscure = !obscure; //<--- here
            });
          },
          icon: Icon(obscure ? Icons.visibility_off : Icons.visibility),
        ),
      ),
      validator: (text) {
        if (text.isEmpty) return 'enter something';

        return null;
      },
      obscureText: index == Index.email ? false : obscure,
    );
  }
}

If anyone can help?

Pokaboom
  • 1,110
  • 9
  • 28
  • I think rebuild should not be blocked by the reason like that. Maybe you need the way to preserve the focus after rebuild. – jeiea Apr 03 '21 at 23:46
  • @jeiea even if I use provider than it also rebuilds whole screen see this https://stackoverflow.com/questions/66672210/flutter-unexpected-behaviour-while-using-flutter-hooks-with-provider – Pokaboom Apr 04 '21 at 09:29
  • I don't care whether or not you use provider, hooks. I think you need to post the code about focus handling. Even if you succeed rebuild small region, still hot reload and other full rebuild situation will still bother you. What I say is all flutter apps should have no problem with full rebuild whenever. – jeiea Apr 04 '21 at 09:41

0 Answers0