How do you change the value inside of a textfield flutter?

后端 未结 10 1678
忘掉有多难
忘掉有多难 2020-12-06 08:49

I have a TextEditingController where if a user clicks a button it fills in with information. I can\'t seem to figure out how to change the text inside of a

10条回答
  •  隐瞒了意图╮
    2020-12-06 09:24

    Here is a full example where the parent widget controls the children widget. The parent widget updates the children widgets (Text and TextField) with a counter.

    To update the Text widget, all you do is pass in the String parameter. To update the TextField widget, you need to pass in a controller, and set the text in the controller.

    main.dart:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Demo',
          home: Home(),
        );
      }
    }
    
    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Update Text and TextField demo'),
            ),
            body: ParentWidget());
      }
    }
    
    class ParentWidget extends StatefulWidget {
      @override
      _ParentWidgetState createState() => _ParentWidgetState();
    }
    
    class _ParentWidgetState extends State {
      int _counter = 0;
      String _text = 'no taps yet';
      var _controller = TextEditingController(text: 'initial value');
    
      void _handleTap() {
        setState(() {
          _counter = _counter + 1;
          _text = 'number of taps: ' + _counter.toString();
          _controller.text  = 'number of taps: ' + _counter.toString();
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Column(children: [
            RaisedButton(
              onPressed: _handleTap,
              child: const Text('Tap me', style: TextStyle(fontSize: 20)),
            ),
            Text('$_text'),
            TextField(controller: _controller,),
          ]),
        );
      }
    }
    

提交回复
热议问题