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

标签 flutter focus textfield

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

天真地,我想写: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.
    );
  }
}

最佳答案

请检查下面的代码,我已经为它使用了 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");
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

并检查下面的输出
enter image description here

关于Flutter:更改 TextField 焦点上的按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61659083/

相关文章:

android - 如何在 Dart/Flutter 中泛化可选参数

java - TreeNode 始终聚焦

jsf - 如何禁用 Primefaces 对话框中第一个输入的焦点?

flutter - 导入问题:日期格式 flutter

将 Firebase 添加到 flutter 应用程序后 iOS 构建失败

java - 检查文本字段是否为空

javascript - 通过单选设置文本字段

javascript - 选项卡按钮在表单文本字段中不起作用

android - flutter : How to prevent rebuild of whole Reorderable Listview?

javascript - 文本框聚焦