简体   繁体   中英

how to change "text" to "text field" when clicking a button in Flutter

There is a regular "Text" and it changes to "TextField" when I click the button I would like to know how to do this

IconButton(
                      icon: Icon(
                        Icons.edit,
                        color: Color(0xFF8D8D8D),
                      ),
                      onPressed: null),

try this

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isTextFild = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            isTextFild ? TextField() : Text('some text'),
            FlatButton(
              child: Text('Show Text Field'),
              onPressed: () {
                setState(() {
                  isTextFild = true;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

This should be enough, a TextFormField that toggles between readOnly and not. This way, you'll ensure that your view doesn't "jump" by switching widgets and you'll be always using the same object, only toggling properties.

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool _isEditing = false;

  void _edit() {
    setState(() => _isEditing = true);
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      readOnly: _isEditing,
    );
  }
}

You can do something like this:

class Sample extends StatefulWidget {
  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  bool _editMode = false;
  @override
  Widget build(BuildContext context) {
    return Row(children: <Widget>[
      _editMode ? TextField(...) : Text(...),
      IconButton(
          icon: Icon(Icons.edit),
          onPressed: () {
            setState(() {
              _editMode = !_editMode;
            });
          })
    ]);
  }
}

Note: If you want to set an initial value for textfield you should use textformfield instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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