我正在使用 Flutter 和 Supabase 在我的应用程序中流式传输帖子。流媒体按预期工作,我可以毫无问题地获取和显示帖子。但是,我在调试控制台中看到以下错误:
DartError:类型错误:“JSArray”的实例:类型“List”不是类型“List”的子类型
这是我的 api 类
class ApiService {
final SupabaseClient _supabaseClient = SupabaseClient(
'MyURL',
'MyAPI');
Stream<List<PostModel>> fetchPosts() {
try {
return _supabaseClient.from('posts').stream(primaryKey: ['id']).asyncMap(
(event) async {
final response = await _supabaseClient
.from('posts')
.select('*,users(*),media(*)')
.order('created_at', ascending: false) as List<dynamic>;
final posts = response
.cast<Map<String, dynamic>>()
.map(
(e) => PostModel.fromJson(e),
)
.toList();
return posts;
},
);
} catch (e) {
rethrow;
}
}
Future<void> addPost({required int userId, required String content}) async {
try {
await _supabaseClient.from('posts').insert({
'user_id': userId,
'content': content,
});
} catch (e) {
rethrow;
}
}
Future<void> deletePost({required int postId}) async {
try {
await _supabaseClient.from('posts').delete().eq('id', postId);
} catch (e) {
rethrow;
}
}
}
这是我的帖子模型
@freezed
class PostModel with _$PostModel {
const factory PostModel({
@JsonKey(name: "id") required int id,
@JsonKey(name: "user_id") required int userId,
@JsonKey(name: "content") required String content,
@JsonKey(name: "created_at") required DateTime createdAt,
@JsonKey(name: "users") required Users users,
@JsonKey(name: "media") required List<Media> media,
}) = _PostModel;
factory PostModel.fromJson(Map<String, dynamic> json) =>
_$PostModelFromJson(json);
}
用户模型
@freezed
class Users with _$Users {
const factory Users({
@JsonKey(name: "id") required int id,
@JsonKey(name: "bio") required String? bio,
@JsonKey(name: "email") required String email,
@JsonKey(name: "state") required String? state,
@JsonKey(name: "country") required String? country,
@JsonKey(name: "website") required String? website,
@JsonKey(name: "username") required String username,
@JsonKey(name: "last_name") required String lastName,
@JsonKey(name: "created_at") required DateTime createdAt,
@JsonKey(name: "first_name") required String firstName,
@JsonKey(name: "profile_picture_url") required String? profilePictureUrl,
}) = _Users;
factory Users.fromJson(Map<String, dynamic> json) => _$UsersFromJson(json);
}
媒体模型
@freezed
class Media with _$Media {
const factory Media({
@JsonKey(name: "id") required int id,
@JsonKey(name: "url") required String url,
@JsonKey(name: "post_id") required int postId,
@JsonKey(name: "comment_id") required dynamic commentId,
@JsonKey(name: "created_at") required DateTime createdAt,
}) = _Media;
factory Media.fromJson(Map<String, dynamic> json) => _$MediaFromJson(json);
}
我发现了这个问题,我还必须在 SUPABASE 中的媒体表和用户表上启用实时功能,而不仅仅是帖子表。并再次重建应用程序,这里消失了。