Flutter:更改 TextField 焦点上的按钮颜色

Flutter: Change button color on TextField focus

我有一个文本字段和一个单独的按钮,我想在文本字段获得焦点时更改按钮的颜色。

天真地想写:FlatButton(..., backgroundColor: myFocusNode.hasFocus ? Colors.red : Colors.green)。当然,这不起作用,因为 Button 不会收到有关焦点更改的通知。或者,我尝试将 Listener 添加到 myFocusNode,但如果我尝试在其中调用 setState 以重建按钮,文本字段将再次失去焦点。

我修改了各自cookbook的示例代码来说明,你可以复制下面的代码并粘贴,运行看看我的意思。单击文本字段时如何使按钮变为红色?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Text Field Focus',
      home: MyCustomForm(),
    );
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Define the focus node. To manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();

    myFocusNode = FocusNode();
  }

  @override
  void dispose() {
    // Clean up the focus node when the Form is disposed.
    myFocusNode.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text Field Focus'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // The first text field is focused on as soon as the app starts.
            TextField(
              autofocus: true,
            ),
            // The second text field is focused on when a user taps the
            // FloatingActionButton.
            TextField(
              focusNode: myFocusNode,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the button is pressed,
        // give focus to the text field using myFocusNode.
        onPressed: () => myFocusNode.requestFocus(),
        tooltip: 'Focus Second Text Field',
        backgroundColor: myFocusNode.hasFocus ? Colors.red : Colors.green,
        child: Icon(Icons.edit),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

myFocusNode.requestFocus(); 在 setState 里面? Ps。是的,它对我有用

myFocusNode = FocusNode();
myFocusNode.addListener(() {
  setState(() {
    if(myFocusNode.hasFocus) {
      myFocusNode.requestFocus();
    }
  });
});

Ps2:@Ravindra Kushwaha 的回答更好:)

请检查下面的代码,我已经为它使用了 Focus 小部件,它有 onFocusChange 表示 TextField 是否被选中

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutterlearningapp/colors.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeScreen();
  }
}

class _HomeScreen extends State<HomeScreen> {
  bool isTextFiledFocus = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Demo",
      home: Scaffold(
        appBar: AppBar(
          title: Text("List"),
        ),
        body: Container(
          margin: EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Focus(
                child: TextFormField(
                  textInputAction: TextInputAction.next,
                  decoration: InputDecoration(labelText: "Input 1"),
                ),
                onFocusChange: (hasFocus) {
                  setState(() {
                    isTextFiledFocus = hasFocus;
                  });
                },
              ),

              TextFormField(
                textInputAction: TextInputAction.next,
                decoration: InputDecoration(labelText: "Input 1"),
              ),
              RaisedButton(
                color: isTextFiledFocus ? Colors.pink : Colors.blue,
                child: Text("Ok"),
                onPressed: () {
                  print("I am clicked");
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

并检查下面的输出