0

这个问题的代码: 在 Flutter 中接收来自弹出导航器的响应, 并添加了 DateTime 选择器表单字段。

如果我们像这样添加 DateFormField:

maind.dart

import 'package:flutter/material.dart';
import 'package:date_field/date_field.dart';
import 'answer.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  Data stateData = Data();
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DateFormField(
              initialDatePickerMode: DatePickerMode.day,
              enabled: true,
            key:_formKey,
            onSaved: (DateTime value)
              {
                stateData.datefield = value;
              },
            validator: (DateTime value){
              return  stateData.datefield != null ? null : 'enter date';
            },
              firstDate: DateTime.now().subtract(Duration(days: 180)),
              lastDate: DateTime.now().add(Duration(days: 365)),

            ),
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData.load = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Data {
  String load;
  DateTime datefield;
}

当 pop 发生时,会出现异常,即在 null 上调用了验证器。和“在最终确定小部件树时引发以下断言:多个小部件使用相同的 GlobalKey。”

如果未使用 key 字段,则不调用验证器。为什么?你如何使用 DateFormField?从包装

日期字段:“^0.1.2”

添加 answer.dart

import 'package:flutter/material.dart';

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed:   () async {
          final holder = await  getFormData(context);
          setState(() {
            data = holder.load;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  Future<Data> getFormData(BuildContext context) async {
    final answer =  await Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
        return (Future.value(answer));
  }
}
4

2 回答 2

0

现在,该软件包的 0.2.0 版本已修复此问题!

于 2020-07-14T15:18:45.767 回答
0

您可以在第 1 步下面复制粘贴运行完整代码
:删除key:_formKey

DateFormField(
          initialDatePickerMode: DatePickerMode.day,
          enabled: true,
          //key:_formKey,

第 2 步:不validator使用value != nullstateData.datefield != null

validator: (DateTime value) {
            //return stateData.datefield != null ? null : 'enter date';
            return value != null ? null : 'enter date';
          },

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';
import 'package:date_field/date_field.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  Data stateData = Data();
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DateFormField(
              initialDatePickerMode: DatePickerMode.day,
              enabled: true,
              //key:_formKey,
              onSaved: (DateTime value) {
                stateData.datefield = value;
              },
              validator: (DateTime value) {
                //return stateData.datefield != null ? null : 'enter date';
                return value != null ? null : 'enter date';
              },
              firstDate: DateTime.now().subtract(Duration(days: 180)),
              lastDate: DateTime.now().add(Duration(days: 365)),
            ),
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value) {
                stateData.load = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context, stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Data {
  String load;
  DateTime datefield;
}

class ShowData extends StatefulWidget {
  @override
  _ShowDataState createState() => _ShowDataState();
}

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            final holder = await getFormData(context);
            print(holder.datefield);
            setState(() {
              data = holder.load;
            });
          },
          elevation: 4,
        ),
        body: Text(
          data,
          style: TextStyle(fontSize: 80),
        ));
  }

  Future<Data> getFormData(BuildContext context) async {
    final answer = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => MyCustomForm()));
    return (Future.value(answer));
  }
}
于 2020-06-03T08:59:42.050 回答