空相关错误 - 参数类型“字符串? Function(String)' 不能分配给参数类型 'String?函数(字符串?)?'

时间:2021-04-30 00:56:07

标签: flutter dart

相同的代码在教程视频中有效,不确定这里发生了什么。我认为这与空安全有关。

我确实尝试过申请?在此解决方案中,但我无法找到有效的解决方案。当我申请 ?方法,验证将不起作用。

如何解决这个问题并构建项目。

这是我运行解决方案时得到的结果 enter image description here

这是包含此示例的视频 URL https://youtu.be/nFSL-CqwRDo enter image description here


这是我的完整代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  //const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coding with Curry',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: FormScreen(),
    );
  }
}

class FormScreen extends StatefulWidget {
  //FormScreen({Key key}) : super(key: key);

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

class _FormScreenState extends State<FormScreen> {
  String _name = "";

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildName() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Name'),
      validator: (String value) {
        if (value.isEmpty) {
          return "Name is Requried";
        }
      },
      onSaved: (String value){
        _name = value;
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Form Demo"),
        ),
        body: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildName(),
                SizedBox(
                  height: 100,
                ),
                RaisedButton(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ),
                    onPressed: () => {
                      if(!_formKey.currentState.validate()){
                        return;
                      }

                      _formKey.currentState.save();

                    })
              ],
            ),
          ),
        ));
  }
}

当我在解决方案中应用null时,我无法编写验证代码 enter image description here

2 个答案:

答案 0 :(得分:6)

当您使用 ? 符号时,您是说该变量可以为空,因此您可以先检查它是否为空,例如:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  //const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coding with Curry',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: FormScreen(),
    );
  }
}

class FormScreen extends StatefulWidget {
  //FormScreen({Key key}) : super(key: key);

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

class _FormScreenState extends State<FormScreen> {
  String _name = "";

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildName() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Name'),
      validator: (String? value) {
        if (value == null || value.isEmpty) {
          return "Name is Requried";
        }
      },
      onSaved: (String? value){
        _name = value!;
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Form Demo"),
        ),
        body: Container(
          margin: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildName(),
                SizedBox(
                  height: 100,
                ),
                RaisedButton(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.blue, fontSize: 16),
                    ),
                    onPressed: () {
                      if(_formKey.currentState!.validate()){
                        return _formKey.currentState!.save();
                      }
                    })
              ],
            ),
          ),
        ));
  }
}

感叹号(例如,_name = value!;)告诉编译器你知道这个可为空的变量永远不会为空。如果它实际上为空,您将看到运行时错误。

您可能还会发现这很有趣:https://flutter.dev/docs/cookbook/forms/validation

答案 1 :(得分:2)

错误:

您收到错误是因为 validator 需要参数类型为可空字符串 (String?) 的函数,但您将其作为不可为空字符串 (String) 传递。例如:

TextFormField(
  validator: (String value) {}, // Error
)

解决方案:

解决方法是提供 String? 或仅省略字符串。

TextFormField(
  validator: (String? value) {}, // No error
)

TextFormField(
  validator: (value) {}, // No error
)