You need to enable JavaScript to run this app. Flutter:登录API JSON响应存入SharedPreferences及通知数组访问问题
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:登录API JSON响应存入SharedPreferences及通知数组访问问题

问题根因

你无法访问unread_notifications数组的核心原因,是自定义的LoginModel没有定义、也没有正确解析该字段,或JSON键名与model解析规则不匹配。

分步实现方案

1. 修正LoginModel解析逻辑

先确保model完整覆盖所有响应字段,兼容数组空值场景,示例代码如下:

// 若仅需要数组长度、不需要数组内的具体字段,可简化元素类型为dynamic
// 若需要读取数组内字段,按实际后端返回结构定义元素类
class UnreadNotification {
  final int id;
  final String title;
  final String content;

  UnreadNotification({
    required this.id,
    required this.title,
    required this.content,
  });

  factory UnreadNotification.fromJson(Map<String, dynamic> json) {
    return UnreadNotification(
      id: json['id'],
      title: json['title'],
      content: json['content'],
    );
  }
}

// 主登录响应Model
class LoginModel {
  final int id;
  final String name;
  final String email;
  final String apiToken;
  final List<UnreadNotification> unreadNotifications;

  LoginModel({
    required this.id,
    required this.name,
    required this.email,
    required this.apiToken,
    required this.unreadNotifications,
  });

  factory LoginModel.fromJson(Map<String, dynamic> json) {
    return LoginModel(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      apiToken: json['api_token'],
      // 做空兼容,后端返回null时默认返回空数组,避免空指针
      unreadNotifications: json['unread_notifications'] == null
          ? []
          : List<UnreadNotification>.from(
              json['unread_notifications'].map(
                (item) => UnreadNotification.fromJson(item),
              ),
            ),
    );
  }
}

若你仅需要数组长度做通知角标,可将unreadNotifications类型简化为List<dynamic>,无需单独定义UnreadNotification类。

2. 存储指定字段到SharedPreferences

拿到解析完成的LoginModel实例后,直接调用SharedPreferences写入对应字段即可,示例代码:

// 初始化SharedPreferences实例
final prefs = await SharedPreferences.getInstance();
// 写入需要持久化的字段
await prefs.setInt('user_id', loginModel.id);
await prefs.setString('user_name', loginModel.name);
await prefs.setString('api_token', loginModel.apiToken);

后续需要读取上述字段时,直接通过prefs.getInt('user_id')、prefs.getString('user_name')、prefs.getString('api_token')获取即可。

3. 主页实现字段展示+通知角标

登录成功跳转主页时,直接将已解析的LoginModel实例传入,无需重复解析JSON。

登录页跳转示例

// 接口请求成功拿到loginModel后执行跳转
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => Homepage(loginModel: loginModel),
  ),
);

主页实现示例

class Homepage extends StatelessWidget {
  final LoginModel loginModel;
  const Homepage({super.key, required this.loginModel});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人主页'),
        actions: [
          // 通知图标+未读数量角标
          Stack(
            alignment: Alignment.center,
            children: [
              IconButton(
                icon: const Icon(Icons.notifications_outlined),
                onPressed: () {},
              ),
              // 仅当存在未读通知时显示角标
              if (loginModel.unreadNotifications.isNotEmpty)
                Positioned(
                  right: 6,
                  top: 6,
                  child: Container(
                    padding: const EdgeInsets.all(2),
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    constraints: const BoxConstraints(
                      minWidth: 18,
                      minHeight: 18,
                    ),
                    child: Text(
                      loginModel.unreadNotifications.length.toString(),
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 展示所有响应字段
            Text('用户ID:${loginModel.id}'),
            Text('用户姓名:${loginModel.name}'),
            Text('用户邮箱:${loginModel.email}'),
            Text('未读通知总数:${loginModel.unreadNotifications.length}'),
            // 如需展示通知详情,可直接遍历unreadNotifications列表渲染
          ],
        ),
      ),
    );
  }
}
常见排查点
  • 核对后端返回JSON中unread_notifications的键名拼写,确保和model中解析的键名完全匹配,避免大小写、下划线错漏
  • 若使用json_serializable、freezed等自动生成model的工具,检查生成的解析文件是否已包含unread_notifications字段的解析逻辑
  • 若接口返回数据嵌套层级异常,检查是否是将外层响应的结构直接传入了LoginModel.fromJson,而非取出嵌套的用户数据层进行解析

内容的提问来源于stack exchange,提问作者Mir Fahim Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 05:45:06