我是颤振的新手。请有人帮助我,我尝试解决此问题,但仍然不知道出了什么问题。我知道这个错误只会错过一些东西,但我不知道在哪里。如果我想使用颤振模型获取数据 api,这是问题吗?无论如何,谢谢你,我希望你们都有美好的一天
<块引用>json
{user: {id: 1, username: kader01, nama: asri sulastri, umur: 23, jenis_kelamin: perempuan, kecamatan_id: 1, created_at: null, updated_at: 2021-05-26T10:16:51.000000Z, avatar: https://www.gravatar.com/avatar/93b96194fa9b4e823df68f7d1fbe15fa}, token: 72|vqtRe6YIKH0LYVCkkcjcIM6XjZGXAArvbiP7LHtg}
<块引用>
用户.dart
class User {
String username, nama, avatar;
User({this.nama, this.username, this.avatar});
User.fromJson(Map<String, dynamic> json)
: nama = json['nama'],
username = json['username'],
avatar = json['avatar'];
}
<块引用>
auth.dart
import 'package:dio/dio.dart' as Dio;
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lentera_app/models/user.dart';
import 'package:lentera_app/services/dio.dart';
class Auth extends ChangeNotifier {
bool _isLoggedIn = false;
User _user;
String _token;
bool get authenticated => _isLoggedIn;
User get user => _user;
void login({Map creds}) async {
print(creds);
try {
Dio.Response response = await dio().post('/loginKader',
data: creds,
options: Options(
followRedirects: false,
validateStatus: (status) {
return status <= 500;
}));
// print(response.data.toString());
String token = response.data.toString();
this.tryToken(token: token);
_isLoggedIn = true;
notifyListeners();
print(token);
} catch (e) {
print(e);
}
}
void tryToken({String token}) async {
if (token == null) {
return;
} else {
try {
Dio.Response response = await dio().get('/user',
options: Dio.Options(headers: {'Authorization': 'bearer $token'}));
this._isLoggedIn = true;
this._user = User.fromJson(response.data);
notifyListeners();
print(_user);
} catch (e) {
print(e);
}
}
}
void logout() {
_isLoggedIn = false;
notifyListeners();
}
}
答案 0 :(得分:0)
您将 String
传递给 fromJson
函数,但其声明的参数类型为 Map
。
User.fromJson(response.data); // data passed to fromJson is String
User.fromJson(Map<String, dynamic> json) // expected argument is Map
要解决此问题,请尝试
使用 dynamic
函数将数据转换为 jsonDecode
import 'dart:convert';
...
User.fromJson(jsonDecode(response.data));
并且不要忘记更新 fromJson
声明中的类型
User.fromJson(dynamic json)
你正在打电话
json['nama'],
但是 nama
位于 user
属性中,因此您应该更好地调用
json['user']['nama'],
相反。
要解决此问题,请尝试更改 fromJson
声明如下
class User {
String username, nama, avatar;
User({this.nama, this.username, this.avatar});
User.fromJson(dynamic json)
: nama = json['user']['nama'],
username = json['user']['username'],
avatar = json['user']['avatar'];
}