我试图将我的TextFormField
逻辑移动到颤振钩子上,所以我有密码字段,我想在其中实现obscure
文本。所以点击按钮它应该隐藏/取消隐藏文本。现在我使用setState()
钩子来做到这一点,但它重建了整个 UI 并将焦点移动到第一个字段,因为我已经为第一个字段设置了 autoFocus,所以我如何确保它只重建特定的 TextFormField。
我的自定义钩子文件,
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,
);
}
}
如果有人可以帮忙?