dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.6
js: ^0.7.1
json_annotation: ^4.9.0
freezed_annotation: ^2.4.4
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^3.0.0
build_runner: ^2.4.11
freezed: ^2.5.2
json_serializable: ^6.8.0
1. 모델 정의 (user_model.dart)
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user_model.g.dart';
part 'user_model.freezed.dart';
@freezed
class User with _$User {
const factory User({
required String id,
required String name,
required int age,
String? email,
@Default([]) List<String> roles,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
해설
@freezed
: 불변 객체를 생성하는 어노테이션
_$User
: Freezed가 생성하는 믹스인
const factory
: 불변 인스턴스 생성을 위한 팩토리 생성자
@Default([])
: 기본값 지정
fromJson
: JSON 변환을 위한 팩토리 메서드
2. JavaScript 서비스 정의
import 'dart:js_interop';
@JS('UserService')
class UserService {
external UserService();
external JSPromise getUserById(String id);
external JSPromise updateUser(JSObject user);
external JSPromise searchUsers(JSObject criteria);
}
해설
@JS()
: JavaScript 클래스/함수와 매핑
external
: 실제 구현은 JavaScript에 있음을 표시
JSPromise
: JavaScript Promise를 나타내는 타입
JSObject
: JavaScript 객체를 나타내는 타입