I am creating an application with flutter and when I want to declare a variable and initialize it after, I have an error
Error: Field '_prenom' should be initialized because its type 'String' doesn't allow null.
import 'package:flutter/material.dart';
class LoginController extends StatefulWidget {
LoginControllerState createState() => new LoginControllerState();
}
class LoginControllerState extends State<LoginController> {
bool _log = true;
String _mail;
String _password;
String _prenom;
String _nom;
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(title: new Text("Authentification"),),
body: new SingleChildScrollView(
child: new Column(
children: <Widget>[
new Container(
margin: EdgeInsets.all(20.0),
width: MediaQuery.of(context).size.width - 40,
height: MediaQuery.of(context).size.height / 2,
child: new Card(
elevation: 8.5,
child: new Column(
children: cardElements(),
),
),
)
],
),
),
);
}
List<Widget> cardElements(){
List<Widget> widgets = [];
widgets.add(
new TextField(
decoration: new InputDecoration(hintText: "Entrez votre adresse mail"),
onChanged: (string) {
setState(() {
_mail = string;
});
},
)
);
widgets.add(
new TextField(
decoration: new InputDecoration(hintText: "Entrez votre mot de passe"),
onChanged: (string) {
setState(() {
_password = string;
});
},
)
);
if(_log == false ) {
widgets.add(
new TextField(
decoration: new InputDecoration(hintText: "Entrez votre prenom"),
onChanged: (string) {
setState(() {
_prenom = string;
});
},
)
);
widgets.add(
new TextField(
decoration: new InputDecoration(hintText: "Entrez votre nom"),
onChanged: (string) {
setState(() {
_nom = string;
});
},
)
);
}
widgets.add(
new TextButton(
onPressed: () {
setState(() {
_log = !_log;
});
},
child: new Text(
(_log == true)
? "Pour créer un compte, appuyez ici"
: "Vous avez déjà un compte ? Appuyez ici"
)
)
);
return widgets;
}
}
Solution 1: Stuck
Dart is null safe . You either must always assign a value or mark it explicitly as nullable using a ?
String _prenom = "Something";
or
String? _prenom;
Solution 2: Zakaria Ferzazi
in Dart class always add ? after DataType
bool? log = true;
String? mail;
String? password;
String? prenom;
String? nom;```