Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 8 TextFiled and for each I want to prescribe a focus so that the color changes. But I have an error - The getter 'hasFocus' was called on null. How can I fixed that?

class _EditAccountScreenState extends State<EditAccountScreen> {
 FocusNode _focusNodeFio;
 FocusNode _focusNodeCompany;
 ...

@override
 void initState() {
   super.initState();
   _focusNodeFio = FocusNode();
   _focusNodeCompany = FocusNode();
  ...
 }

 @override
 void dispose() {
   _focusNodeFio.dispose();
   _focusNodeCompany.dispose();
 ...
   super.dispose();
 }
@override
 Widget build(BuildContext context) {
.......
Padding(
               child: TextField(
                 focusNode: _focusNodeFio,
                 onTap: () {
                   setState(() {
                     FocusScope.of(context).requestFocus(_focusNodeFio);
                   });
                 },
                 decoration: InputDecoration(
                   labelText: 'Contacts',
                   labelStyle: TextStyle(
                       color: _focusNodeFio.hasFocus ? Colors.teal[300] : Colors.grey
                   ),
                   contentPadding:

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
642 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is working!

final FocusNode _fNode = FocusNode();
  
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: TextField(
      focusNode: _fNode,
      onTap: () => FocusScope.of(context).requestFocus(_fNode),
      decoration: InputDecoration(
        labelText: 'Contacts',
        labelStyle: TextStyle(color: _fNode.hasFocus ? Colors.teal[300] : Colors.grey),
      ),
    ),
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...