I have just started using Flutter and i’m having this problem while running my code "Another exception Null’ is not a subtype of type ‘String’ in typecast Another exception when i cast the data as a string i tried to cast the data into String but error is not gone
here is my code can you help me with that
login.dart
import 'package:e_commers_with_stripe/utils/login_data.dart';import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class LogInScreen extends StatefulWidget {
const LogInScreen({super.key});
@override
State<LogInScreen> createState() => _LogInScreenState();
}
class _LogInScreenState extends State<LogInScreen> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _loadingButton = false ;
Map<String, String> data = {};
_LoaginScreenState(){
data = LoginData.sigIn;
}
void switchLogin(){
setState(() {
if(mapEquals(data, LoginData.sigUp)){
data = LoginData.sigIn;
}else{
data = LoginData.sigUp;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(padding: EdgeInsets.only(bottom: 8),
child: Text(data["heading"] as String,
style: Theme.of(context).textTheme.headlineLarge,),)
],
),
), );
}
}
and login_data.dart
class LoginData{
static Map<String, String> sigIn = {
"heading": "Getting Started",
"subHeading": "Create an account to continue",
"lable": "Sign In",
"footer": "Create a new account ? Sign Up",
};
static Map<String, String> sigUp= {
"heading": "Welcome Back !",
"subHeading": "Use your account email and password",
"lable": "Sign Up",
"footer": "Already have an account ? Sign In",
};
}
2
Answers
This is because the ‘headlight’ key in the data variable is null, and you are trying to assign null to a field whose value is the required string.
Try this;
or
Change this;
To;
I was a little confused when I did some research. When you use the constructor of the State class, it runs before initState. However, depending on the performance of the device, the assignment time of the data variable may change and it may remain null. Here is the ‘??’ statement will prevent you from getting an error, but there will be no refresh operation when the value arrives. I think if you know whether the user is a new or existing user, pass a parameter to the LoginView page.
change code