使用Flutter与Supabase登录时遇Type <Null> is not a subtype of Map<String, dynamic>错误
Flutter + Supabase登录报错:Type is not a subtype of Map<String, dynamic> 解决方法
问题根源分析
这个错误主要来自三个核心问题:字段赋值错误、未处理数据库查询空结果、未处理JSON字段为null的情况。
具体修复步骤
修正UserModel.fromJson的字段赋值错误
你在fromJson里错误地将email赋值为json['follower_count'],这不仅类型不匹配(follower_count是int类型,email是String类型),还会导致后续字段取值混乱。处理数据库查询结果为空的情况
从users表查询用户数据时,可能存在查询不到结果的场景,直接调用userData.first会抛出异常,同时要确保返回的JSON字段不为null。为可能为null的字段添加默认值
数据库中的字段可能为null,需要用??为数字类型字段设置默认值;userInfo字段如果为null,要传入空Map避免UserInfoModel.fromJson接收null值。
修正后的代码
UserModel
class UserModel extends User { final UserInfoModel userInfo; final String email; final String username; final int totalPosts; final int follower_count; final int following_count; UserModel({ this.totalPosts = 0, this.follower_count = 0, this.following_count = 0, required this.email, required this.username, required this.userInfo, }) : super( email: email, username: username, userInfo: userInfo, ); factory UserModel.fromJson(Map<String, dynamic> json) { return UserModel( // 处理userInfo为null的情况,传入空Map避免类型错误 userInfo: UserInfoModel.fromJson(json['userInfo'] ?? {}), // 为数字字段设置默认值,防止null转int报错 totalPosts: json['totalPosts'] ?? 0, // 修正email的取值字段 email: json['email'] ?? '', follower_count: json['follower_count'] ?? 0, following_count: json['following_count'] ?? 0, username: json['username'] ?? '', ); } Map<String, dynamic> toJson() { return { 'userInfo': userInfo.toJson(), 'totalPosts': totalPosts, 'follower_count': follower_count, 'following_count': following_count, 'email': email, 'username': username, }; } }
登录方法
@override Future<UserModel> logInWithEmailPassword({ required String email, required String password, }) async { try { final response = await supabaseClient.auth.signInWithPassword( password: password, email: email, ); if (response.user == null) { throw const ServerException('User is null!'); } final userData = await supabaseClient .from('users') .select() .eq('uid', response.user!.id); // 检查查询结果是否为空,提前抛出异常 if (userData.isEmpty) { throw const ServerException('User data not found in database!'); } return UserModel.fromJson(userData.first); } on AuthException catch (e) { throw ServerException(e.message); } catch (e) { throw ServerException(e.toString()); } }
额外检查
确保你的UserInfoModel.fromJson方法能正确处理空Map({}),如果UserInfoModel的字段都是必填项,也要为其添加默认值处理,避免出现同样的null类型错误。
内容的提问来源于stack exchange,提问作者Ddd279
相关产品推荐
相关产品推荐

