简体   繁体   中英

In Flutter, I want to get current date with button press and show in a Textfield, How can I do this?

I want to get current date with button "Get Date" press and show in a Textfield as in the image below, Is it possible? How can I do this ? Pls help newbie here....

在此处输入图片说明

class _Home2State extends State<Home2> {
  DateTime date;
  final amount = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'mytest1',
      home: Scaffold(
        body: Card(
          child: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(labelText: 'Amount'),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      // onChanged: ???,
                      decoration: InputDecoration(labelText: 'Date'),
                    ),
                  ),
                  RaisedButton(
                    color: Colors.blue,
                    child: Text(
                      'Get Date',
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () => setState(
                      () {
                        date = new DateTime.now();
                        print(date);
                      },
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

I want to get current date with button "Get Date" press and show in a Textfield as in the image below,

First, assign your controller to the desired TextField like controller: amount .

Second, add amount.text = '$date'; in your setState()

  DateTime date;
  final amount = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        children: <Widget>[
          TextField(
            decoration: InputDecoration(labelText: 'Amount'),
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: TextField(
                  controller: amount,
                  decoration: InputDecoration(labelText: 'Date'),
                ),
              ),
              RaisedButton(
                color: Colors.blue,
                child: Text(
                  'Get Date',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () => setState(
                  () {
                    date = DateTime.now();
                    amount.text = '$date';
                  },
                ),
              )
            ],
          )
        ],
      ),
    );
  }

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