I am linking cloud function to my Flutter model. Result is coming from Cloud-Function
print(result.data);
print(result.data.runtimeType);
GameModel _incomingGame = GameModel.fromJson(result.data);
print(result.data);
{
game: 'GTA',
played: ['ISODATE', ...]
}
print(result.data.runtimeType);
flutter: _InternalLinkedHashMap<String, dynamic>
GameModel
@JsonSerializable()
class GameModel {
String? game;
List? played;
GameModel(
this.game,
this.played,);
factory GameModel.fromJson(Map<String, dynamic> json) =>
_$GameModelFromJson(json);
Map<String, dynamic> toJson() => _$GameModelToJson(this);
}
game_model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'game_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GameModel _$GameModelFromJson(Map<String, dynamic> json) => GameModel(
json['game'] as String?,
json['played'] as List?,
);
Map<String, dynamic> _$GameModelToJson(GameModel instance) => <String, dynamic>{
'game': instance.game,
'played': instance.played,
};
The incoming data result's runtimeType shows that it is Map<String, dynamic>
in the console. However, when I execute GameModel.fromJson()
, it causes type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' in type cast
.
I really don't get that why this is happening somehow? Even if I do something like below also causes the same type cast error.
GameModel _gameData = result.data;
var game = GameModel.fromJson(_gameData);
Is there any way that I can fix this?
CodePudding user response:
Try these solutions
GameModel _incomingGame = GameModel.fromJson(result.data as Map<String, dynamic>);
Or
GameModel _incomingGame = GameModel.fromJson(Map<String, dynamic>.from(result.data));
It also would be better if you check the types before executing type casts
If above solutions doesn't work, add the type when calling cloud functions
final func = FirebaseFunctions.instance.httpsCallable('gameFunction');
final result = await func<Map<String, dynamic>?>();
CodePudding user response:
Try this solution:
GameModel.fromJson((result.data as Map<dynamic, dynamic>).cast<String, dynamic>())