Disable a text edit field in flutter

后端 未结 11 1572
深忆病人
深忆病人 2020-12-23 17:05

I need to disable TextFormField occasionally. I couldn\'t find a flag in the widget, or the controller to simply make it read only or disable. What is the best way to do it?

11条回答
  •  攒了一身酷
    2020-12-23 17:20

    This isn't a feature that is currently provided by the framework, but you can use a FocusScope to prevent a TextFormField from requesting focus.

    Here's what it looks like when it's disabled.

    (with hint text)

    (with a readonly value)

    Here's what it looks like when it's enabled.

    (with focus)

    (without focus)

    Code for this is below:

    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 {
    
      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',
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
    

提交回复
热议问题