简体   繁体   中英

Flutter - How make selected value inside DatePicker to appear inside a TextFormField?

What I did so far: I have an onTap () action inside a TextFormField. This onTap () action calls the _selectDate that opens the datepicker. Inside the _selectDate I'm using an auxiliary variable that I created called presentText and I assign this variable inside the initialValue of the TextFormField. The problem is that the initialValue is always blank, even if I change the date inside the datepicker, TextFormField's initialValue remains blank. In the debug I saw that the presentText is filled in correctly but I don't know why the value is not going to the TextFormField.

   class _DetailFormState extends State<DetailForm> {
              DateTime selectedDate = DateTime.now();
              String presentText;

              Future<Null> _selectDate(BuildContext context) async {
                final DateTime picked = await showDatePicker(
                    context: context,
                    initialDate:
                        widget.user.birthday != null ? widget.user.birthday : selectedDate,
                    firstDate: DateTime(2015, 8),
                    lastDate: DateTime(2101));
                if (picked != null && picked != selectedDate)
                  setState(() {
                    selectedDate = picked;
                    widget.user.birthday = picked;
                    presentText = "${widget.user.birthday.toLocal()}" != null
                        ? "${widget.user.birthday.toLocal()}".split(' ')[0].toString()
                        : "${selectedDate.toLocal()}".split(' ')[0].toString();
                  });
              }

              @override
              Widget build(BuildContext context) {
                return Scaffold(
                  body: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    child: Form(
                      key: _formKey,
                      autovalidate: true,
                      child: Column(
                        children: <Widget>[

                             Padding(
                              padding: EdgeInsets.only(top: 15),
                              child: Text(
                                'Birthday',
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(fontWeight: FontWeight.bold),
                              )),

                          GestureDetector(
                              onTap: () => _selectDate(context),
                              child: AbsorbPointer(
                                  child: TextFormField(
                                initialValue: presentText
                              ))),
                               ],
                  ),
                ],
              ),
            ),
          ),
        );
      }

you must use a controller in the TextFormField in this case like this:

 DateTime selectedDate = DateTime.now();
              TextEditingController controller = TextEditingController();
              String presentText;

              void _selectDate() async {
                final DateTime picked = await showDatePicker(
                    context: context,
                    initialDate:DateTime.now(),
                    firstDate: DateTime(2015, 8),
                    lastDate: DateTime(2101));
                if (picked != null && picked != selectedDate)
                  setState(() {
                    selectedDate = picked;
                    controller.text=picked.toString();
                  });
              }

              @override
              Widget build(BuildContext context) {
                return Scaffold(
                  body: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    child: Form(
                      autovalidate: true,
                      child: Column(
                        children: <Widget>[
                             Padding(
                              padding: EdgeInsets.only(top: 15),
                              child: Text(
                                'Birthday',
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(fontWeight: FontWeight.bold),
                              )),
                          GestureDetector(
                              onTap: () => _selectDate(),
                              child: AbsorbPointer(
                                  child: TextFormField(
                                    controller: controller,
                                initialValue: presentText,
                              ))),
                               ],
                  ),
              ),
            ),
          );
      }

You can copy paste run full code below
You can use TextEditingController

code snippet

final myController = TextEditingController();

myController.text = "${widget.user.birthday.toLocal()}" != null
            ? "${widget.user.birthday.toLocal()}".split(' ')[0].toString()
            : "${selectedDate.toLocal()}".split(' ')[0].toString();

AbsorbPointer(
                      child: TextFormField(controller: myController

working demo

在此处输入图像描述

full code

import 'package:flutter/material.dart';

class User {
  DateTime birthday;

  User({this.birthday});
}

class DetailForm extends StatefulWidget {
  User user;

  DetailForm({this.user});
  @override
  _DetailFormState createState() => _DetailFormState();
}

class _DetailFormState extends State<DetailForm> {
  DateTime selectedDate = DateTime.now();
  String presentText;
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();

  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate:
            widget.user.birthday != null ? widget.user.birthday : selectedDate,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
        widget.user.birthday = picked;
        myController.text = "${widget.user.birthday.toLocal()}" != null
            ? "${widget.user.birthday.toLocal()}".split(' ')[0].toString()
            : "${selectedDate.toLocal()}".split(' ')[0].toString();
      });
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
        child: Form(
          key: _formKey,
          autovalidate: true,
          child: Column(
            children: <Widget>[
              Padding(
                  padding: EdgeInsets.only(top: 15),
                  child: Text(
                    'Birthday',
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  )),
              GestureDetector(
                  onTap: () => _selectDate(context),
                  child: AbsorbPointer(
                      child: TextFormField(controller: myController
                          //initialValue: presentText
                          ))),
            ],
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: DetailForm(user: User()),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

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