我需要偶尔禁用TextFormField.我在小部件中找不到一个标志,也找不到简单地将其设为只读或禁用的控制器.

推荐答案

这不是框架当前提供的功能,但是您可以使用FocusScope来阻止TextFormField请求焦点.

这是它被禁用时的样子.

(带提示文本)

(具有只读值) readonly

以下是它启用时的外观.

(带焦点) focused

(无焦点) editable

此操作的代码如下:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {

  TextEditingController _controller = new TextEditingController();
  bool _enabled = false;

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Disabled Text'),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.free_breakfast),
        onPressed: () {
          setState(() {
            _enabled = !_enabled;
          });
        }
      ),
      body: new Center(
        child: new Container(
          margin: const EdgeInsets.all(10.0),
          child: _enabled ?
          new TextFormField(controller: _controller) :
          new FocusScope(
            node: new FocusScopeNode(),
            child: new TextFormField(
              controller: _controller,
              style: theme.textTheme.subhead.copyWith(
                color: theme.disabledColor,
              ),
              decoration: new InputDecoration(
                hintText: _enabled ? 'Type something' : 'You cannot focus me',
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Flutter相关问答推荐

Android Emulator冻结,但在调整窗口大小时解冻

如何在WidgetRef引用外部的函数中使用Riverpod刷新数据

我不能通过第5步了解Flutter 翼Firebase教程

Flutter 布局-全屏幕容器

如何使文本表格域在抖动中变圆?

GetConnect Post API调用在Flutter Web中不起作用说:415不支持的媒体类型

将记录/元组用作SplayTreeMap中的键

在Dart中使用Riverpod代码生成时出现问题(addListener)

如何在 Flutter 中以背景 colored颜色 制作圆圈的一部分

Select 文本时如何更改 Flutter 中的光标 colored颜色 ?

在允许屏幕 Select 和点击的同时保持通用对话框显示

Flutter屏幕适配 - 在模拟器和真实手机上文本尺寸不同

使用 riverpod 提供 GoRouter 实例的正确方法是什么?

从子集合sem中获取参考学年&&课程名称的值

Android Electric eel Mac M1:运行 flutter doctor -v 时无法找到Bundle 的 java 版本

Flutter 构建方法使用的是旧版本的变量?

如何在 Flutter 中将列小部件添加到行小部件?

扫描flutter生成的二维码后如何弹出文本字段值

TextSpan 避免符号字符串组上的换行符

如何从我的Flutter 项目中删除错误?