我正在 Flutter 中创建一个登录表单并使用 mongodb 作为数据库。
这是我的认证文件代码
import 'dart:convert';
import 'package:attendance_system_app/Screens/Dashboard/Employee_Dashboard.dart';
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
class AuthService{
Dio dio=new Dio();
var localhost_url="http://10.0.2.2:8000/login";
var heroku_Url="https://attendance-demo.herokuapp.com/login";
login(name,password) async{
Map<String,dynamic> data={
'username':name,
'password':password
};
await dio
.post(localhost_url,data: json.encode(data))
.then((onResponse){
print(onResponse.data);
// EmployeeDashboard();
}).catchError((onerror){
print(onerror.toString());
});
}
}
在这里我在登录按钮上调用上面的代码
RoundedButton(text:" Login", press: () {
AuthService().login(name,password).then((value){
if(value.data['success']){
token=value.data['token'];
Fluttertoast.showToast(msg: 'Authenticated',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
//here i call the dashboard when credentials are correct
Navigator.push(
context,
MaterialPageRoute(builder: (context) => EmployeeDashboard()),
);
我的服务器已成功连接,并且 api 在邮递员上运行良好。当我输入用户名和密码时,我得到了与该用户名相关的详细信息作为终端输出,而且我也收到此错误。
错误:
Unhandled Exception: NoSuchMethodError: The getter 'data' was called on null.
E/flutter (13740): Receiver: null
E/flutter (13740): Tried calling: data
这是输出的快照
如果有人知道解决方案以及我做错的地方,请帮忙!谢谢。
答案 0 :(得分:2)
让我在登录功能中简单化你没有返回任何值
当你在登录函数中返回一些数据时
在您的代码值中有一些数据
没有任何数据,您正在调用 value.data['sucess']
因此在您的登录功能中返回一些值
答案 1 :(得分:1)
只需从 then
处理程序返回响应:
await dio
.post(localhost_url,data: json.encode(data))
.then((onResponse){
print(onResponse.data);
return onResponse; // <--- HERE
}).catchError((onerror){
print(onerror.toString());
});
我还建议您尽可能在代码中使用显式类型而不是动态类型。代码将更具可读性,并且更容易处理对象。示例:
Response<Map<String, dynamic>> login(String name, String password) async{
...
答案 2 :(得分:0)
这就是我所做的!
Future save() async {
Dio dio=new Dio();
var data={
'username': user.username,
'password': user.password
};
await dio
.post(localhost_url,data: json.encode(data))
.then((onResponse){
print(onResponse.data);
}).catchError((onerror){
print(onerror.toString());
});
Navigator.push(
context, new MaterialPageRoute(builder: (context) => EmployeeNavigation()));
}
User user = User('', '');
User.dart 文件
class User {
String username;
String password;
User(this.username, this.password);
}
登录按钮代码
RoundedButton(text:"Login", press: () {
save();
}
请建议这样做是否合适!