代码之家  ›  专栏  ›  技术社区  ›  Dzy

Flutter“String”不是类型“Map<dynamic,dynamic>”的子类型

  •  0
  • Dzy  · 技术社区  · 1 年前

    我是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"
    }
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   DroidFlutter    1 年前

    确保响应处理正确反映API返回的JSON结构。

    try {
          Response<dynamic> 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) {
            if (response.data is Map<String, dynamic>) {
              Map<String, dynamic> responseData = response.data;
              Map<String, dynamic> data = responseData['data'];
              token = data['token'];
              return true;
            } else {
              throw Exception('Failed to parse data');
            }
          } else if (response.statusCode == 401) {
            throw Exception(response.data['message'] ?? 'Unauthorized');
          } else {
            throw Exception('Failed to login');
          }
        } on DioError catch (e) {
          if (e.response?.statusCode == 401) {
            print('Error 401: ${e.response?.data}');
            } else {
            print('Error: ${e.toString()}');
           }
        } catch (e) {
          print('Error: ${e.toString()}');
         }