Programming Framework/Flutter
[Flutter] Yaml 파일 Decode/DeSerialize(Yaml 객체화)
HoZang
2024. 5. 26. 13:40
[Flutter] Yaml 파일 Decode/DeSerialize(Yaml 객체화)
아래 코드는 yaml 파일로부터 읽어온 데이터를 GetIt ServiceLocator에 저장 하는 과정까지의 코드이다.
http 통신에 사용할 서버 정보를 yaml파일로 설정하기 위한 예시이다.
import 'package:get_it/get_it.dart';
import 'package:hello_world/services/config_service.dart';
import "package:flutter/services.dart" as services;
import "package:yaml/yaml.dart";
Future<void> serviceConfig() async {
final String data = await services.rootBundle.loadString('server.yaml');
final YamlMap mapData = loadYaml(data);
final Server server = Server.fromYaml(mapData);
final ConfigService configService = ConfigService(server: server);
GetIt.I.registerSingleton<ConfigService>(configService);
}
class Server {
const Server({
required this.protocol,
required this.host
});
final String protocol;
final String host;
factory Server.fromYaml(YamlMap yaml) => Server(
protocol: yaml['protocol'] ?? '',
host: yaml['host'] ?? ''
);
}
class ConfigService {
ConfigService({required this.server});
final Server server;
}