我正在使用提供程序实现登录,但我没有在仪表板页面上获取数据。型号类别
class LoginModel {
Data data;
int status;
String message;
LoginModel({this.data, this.status, this.message});
LoginModel.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
status = json['status'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.toJson();
}
data['status'] = this.status;
data['message'] = this.message;
return data;
}
}
class Data {
String customerId;
String customerMobileNo;
String customerToken;
String otp;
Data({this.customerId, this.customerMobileNo, this.customerToken, this.otp});
Data.fromJson(Map<String, dynamic> json) {
customerId = json['customerId'];
customerMobileNo = json['customerMobileNo'];
customerToken = json['customerToken'];
otp = json['otp'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['customerId'] = this.customerId;
data['customerMobileNo'] = this.customerMobileNo;
data['customerToken'] = this.customerToken;
data['otp'] = this.otp;
return data;
}
}
提供商类别
class AuthProvider extends ChangeNotifier {
Future<LoginModel> generateOTP(String mobileNumber) async {
var result;
Response response = await post(
AppUrl.login,
body: {
'mobileNo': mobileNumber,
},
);
if(response.statusCode==200) {
final responseData = json.decode(response.body);
var userData = responseData['data'];
print(responseData);
LoginModel authUser = LoginModel.fromJson(userData);
notifyListeners();
}
else {
print("Something went wrong");
}
return result;
}
}
显示页面
class Dashboard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final userTest = Provider.of<AuthProvider>(context);
return Scaffold(
body: Center(
child: ListView(
shrinkWrap: true,
children: [
Text(userTest.authUser.data.customerToken),
],
),
),
);
}
错误
在处理手势时引发了以下NoSuchMethodError:对null调用了getter"customerToken"。接收方:空尝试调用:customerToken
如何访问LoginModel类的属性。有人能解决我的问题吗?请帮助我,我试了很多次,但都没有得到价值。
- 您不能用普通的Future函数通知您的侦听器(不过,我不确定,因为您没有提供提供者类的完整代码(。您必须将
generateOTP()
函数放在changenotifier类中,该类将帮助您在需要时通知侦听器,并使其作用域为您的小部件 - 您收到此错误是因为您没有将令牌存储在任何位置,或者在使用之前没有调用存储令牌。因此,首先,请尝试存储令牌并在使用之前调用它
LoginModel authUser = LoginModel.fromJson(userData);
您正在初始化方法变量LoginModel authUser
而不是类变量authUser
的值,请尝试从"authUser"之前删除LoginModel
- 在
Dashboard
中,您还应该检查null
值,您可以这样做userTest?.authUser?.data?.customerToken ?? ''