坏:错误:应初始化字段“_prenom”,因为其类型“String”不允许为 null

et1*_*00_ 3 dart flutter

我正在使用 flutter 创建一个应用程序,当我想声明一个变量并在之后初始化它时,出现错误

\n
\n

错误:应初始化字段“_prenom”,因为其类型“String”不允许为 null。

\n
\n
import 'package:flutter/material.dart';\n\nclass LoginController extends StatefulWidget {\nLoginControllerState createState() => new LoginControllerState();\n}\n\nclass LoginControllerState extends State<LoginController> {\n\nbool _log = true;\nString _mail;\nString _password;\nString _prenom;\nString _nom;\n\n@override\nWidget build(BuildContext context) {\n// TODO: implement build\nreturn new Scaffold(\n  appBar: new AppBar(title: new Text("Authentification"),),\n  body: new SingleChildScrollView(\n    child: new Column(\n      children: <Widget>[\n        new Container(\n          margin: EdgeInsets.all(20.0),\n          width: MediaQuery.of(context).size.width - 40,\n          height: MediaQuery.of(context).size.height / 2,\n          child: new Card(\n            elevation: 8.5,\n            child: new Column(\n              children: cardElements(),\n            ),\n          ),\n        )\n      ],\n    ),\n  ),\n);\n}\n\nList<Widget> cardElements(){\nList<Widget> widgets = [];\n\nwidgets.add(\n  new TextField(\n    decoration: new InputDecoration(hintText: "Entrez votre adresse mail"),\n    onChanged: (string) {\n      setState(() {\n        _mail = string;\n      });\n    },\n  )\n);\nwidgets.add(\n    new TextField(\n      decoration: new InputDecoration(hintText: "Entrez votre mot de passe"),\n      onChanged: (string) {\n        setState(() {\n          _password = string;\n        });\n      },\n    )\n);\n\nif(_log == false ) {\n  widgets.add(\n      new TextField(\n        decoration: new InputDecoration(hintText: "Entrez votre prenom"),\n        onChanged: (string) {\n          setState(() {\n            _prenom = string;\n          });\n        },\n      )\n  );\n  widgets.add(\n      new TextField(\n        decoration: new InputDecoration(hintText: "Entrez votre nom"),\n        onChanged: (string) {\n          setState(() {\n            _nom = string;\n          });\n        },\n      )\n  );\n}\n\nwidgets.add(\n  new TextButton(\n      onPressed: () {\n        setState(() {\n          _log = !_log;\n        });\n      },\n      child: new Text(\n          (_log == true)\n              ? "Pour cr\xc3\xa9er un compte, appuyez ici"\n              : "Vous avez d\xc3\xa9j\xc3\xa0 un compte ? Appuyez ici"\n      )\n  )\n);\nreturn widgets;\n}\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Stu*_*uck 11

Dart 是空安全的。您要么必须始终分配一个值,要么使用?

String _prenom = "Something";
Run Code Online (Sandbox Code Playgroud)

或者

String? _prenom;
Run Code Online (Sandbox Code Playgroud)