简体   繁体   English

Flutter:更改文本字段焦点上的按钮颜色

[英]Flutter: Change button color on TextField focus

I have a text field and a separate button, I want to change the button's color when the text field focuses.我有一个文本字段和一个单独的按钮,我想在文本字段聚焦时更改按钮的颜色。

Naively, I would like to write: FlatButton(..., backgroundColor: myFocusNode.hasFocus? Colors.red: Colors.green) .天真地,我想写: FlatButton(..., backgroundColor: myFocusNode.hasFocus? Colors.red: Colors.green) This, of course, does not work as the Button doesn't get notified about the focus change.当然,这不起作用,因为 Button 不会收到有关焦点更改的通知。 Alternatively, I tried to add a Listener to myFocusNode , but if I try to call setState inside it in order to rebuild the button, the text field loses it's focus again.或者,我尝试向myFocusNode添加一个Listener ,但如果我尝试在其中调用setState以重建按钮,则文本字段会再次失去焦点。

I modified the sample code from the respective cookbook to illustrate, you can copy the code below and paste and run to see what I mean.我修改了相应食谱中的示例代码以进行说明,您可以复制下面的代码并粘贴并运行以了解我的意思。 How can i make the button turn red when clicking the text field?单击文本字段时如何使按钮变为红色?

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.
    );
  }
}

Please check the below code, i have use the Focus widget for it, it has the onFocusChange which will indicate the TextField is selected or not请检查下面的代码,我已经使用了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");
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

And check the below output of it并检查下面的output
在此处输入图像描述

myFocusNode.requestFocus(); inside setState?在setState里面? Ps.附言。 Yep it worked for me是的,它对我有用

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

Ps2: @Ravindra Kushwaha answer is better:) Ps2:@Ravindra Kushwaha 答案更好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM