我是flutter dev的初学者,我有一个项目需要使用api进行登录,但我面临着这样的错误:
type 'String' is not a subtype of type 'Map<dynamic, dynamic>'
有人能帮我解决上面的问题吗?
这是我的代码:
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
class AuthService {
static String? token;
Future<bool> login({
required String email,
required String password,
}) async {
try {
var response = await Dio().post(
"http://my-api/index/login",
options: Options(
headers: {
"Content-Type": "application/json",
},
),
data: {
"email": email,
"password": password,
},
);
if (response.statusCode == 200) {
Map obj = response.data;
token = obj["data"]["token"];
return true;
} else {
throw Exception('Failed to login');
}
} on DioException catch (e) {
if (e.response?.statusCode == 401) {
debugPrint('Error 400: ${e.response?.data}');
throw Exception('Invalid email or password');
} else {
debugPrint('Error: ${e.toString()}');
throw Exception('Failed to login');
}
}
}
}
以下是API的结构:
{
"status": 200,
"message": "login success",
"data": {
"id": "622b",
"email": "[email protected]",
"roleId": "a11ea",
"biodateId": "ba2",
"createdAt": "2024",
"updatedAt": "2024",
"token": "token" }
}
如果出现错误:
{
"status": 401,
"message": "Wrong Password"
}