How to use late final keyword in Flutter Dart freezed model ?
This code generates successfully and has no static analysis error but it does not compile strangely.
import 'dart:convert';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'fb_story.freezed.dart';
part 'fb_story.g.dart';
@freezed
class FbStory with _$FbStory {
FbStory._();
const factory FbStory({
required String id,
required String data_str,
@Default(false) bool imageNotAvailable,
@Default(false) bool videoNotAvailable,
String? imageUrl,
String? videoUrl,
}) = _FbStory;
late final Map<String, dynamic> data = jsonDecode(data_str);
factory FbStory.fromJson(Map<String, dynamic> json) =>
_$FbStoryFromJson(json);
}
Error:
Error: A constant constructor can't call a non-constant super constructor.
Before, Freezed used to pioneer the late
keyword with @late
annotation so I guess there should be a way to make this work. class is still freezed, just lazy
Just remove const at factory FbStory
Full code:
import 'dart:convert';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'fb_story.freezed.dart';
part 'fb_story.g.dart';
@freezed
class FbStory with _$FbStory {
FbStory._();
factory FbStory({
required String id,
required String data_str,
@Default(false) bool imageNotAvailable,
@Default(false) bool videoNotAvailable,
String? imageUrl,
String? videoUrl,
}) = _FbStory;
late final Map<String, dynamic> data = jsonDecode(data_str);
factory FbStory.fromJson(Map<String, dynamic> json) =>
_$FbStoryFromJson(json);
}