I'm trying to display the name of the user on another page after he/she login. I have no problem displaying the code or message on another page. But when I tried to display the name or the email I got a null value. This is the response of print(data['name']); -> I/flutter ( 4896): null
and this is the response of print(data['code']); -> I/flutter ( 4896): 0
. I tried to add this ?? ''
like this one pageRoute(data['name'] ?? '');
to avoid this error below:
E/flutter ( 4896): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
E/flutter ( 4896): #0 _MyHomePageState.login (package:login/main.dart:99:23)
E/flutter ( 4896): <asynchronous suspension>
I'm still getting a null when the user login. This is the response of the URL if the user enters the correct email and password.
I/flutter ( 4896): 200
I/flutter ( 4896): {"code":0,"message":"success","data":{"Id":121106,"Name":"John",
"Email":"[email protected]","Token":"4ca34eb1-0416-43f9-8d3e-19ed51d64288"}}
This is my code below:
Future<void> login() async {
if(emailController.text.isNotEmpty && passController.text.isNotEmpty) {
var headers = {"Content-type": "application/json"};
var myBody = {
'email' : emailController.text,
'password' : passController.text,
};
var response = await http.post(Uri.parse("url"),
headers: headers,
body: jsonEncode( myBody ));
final data = jsonDecode(response.body);
if(response.statusCode == 200 && data['code'] == 0) {
pageRoute(data['name'] ?? '');
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Invalid Credentials.")));
}
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Blank Field Not Allowed")));
}
}
void pageRoute(String name) async {
//here we store value inside shared preferences
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString("login", name);
Navigator.push(context, MaterialPageRoute(builder: (context) => const Home()));
}
}
home.dart
String name= "";
@override
void initState() {
// TODO: implement initState
super.initState();
getName();
}
Future<void> getName() async {
//here we fetch our credentials from shared pref
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
name = pref.getString("login")!;
});
}
//
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: SafeArea(
child: Center(
child: Column(
children: [
Image.asset(
'profile_image.jpg', height: 150, width: 150,),
const SizedBox(height: 15,),
Text("Welcome: $name"), //still null
const SizedBox(height: 15,),
const Text('Logout'),
],
)
)
),
),
)
);
CodePudding user response:
change data['name']
to data['data']['Name']
CodePudding user response:
yeah, changing data['name'] to data['data']['Name'] would definitely solve your problem.