티스토리 뷰

[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;
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함