Skip to the content.

Flutter & Vue 데이터 동기화

Flutter와 Vue를 이용해서 하이브리드 앱을 개발할 때 데이터를 공유하는 방법에 대해서 설명합니다.

개요

데이터의 저장 및 복원은 앱에서 담당하고 웹은 앱의 데이터를 전달받아서 사용하는 형식입니다.

Vue 파트

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
31
32
import store from "@/store";
import bridgeOut from "@/bridge-out";

let syncData = {
    memberInfo: {},
};

export default {
    init() {
        window.syncGlobals = this.syncGlobals;
    },

    syncGlobals(params) {
        syncData = JSON.parse(window.atob(params));
        console.log(JSON.stringify(syncData));
        store.dispatch("main/setMemberInfo", syncData.memberInfo);
    },

    getData() {
        return syncData;
    },

    update() {
        bridgeOut.syncGlobals(syncData);
    },

    setMemberInfo(value) {
        syncData.memberInfo = value;
        store.dispatch("main/setMemberInfo", syncData.memberInfo);
        update();
    },
}

Flutter 파트

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Globals {
  static final Globals _instance = Globals._internal();

  factory Globals() {
    return _instance;
  }

  Globals._internal() {
    Bridge().subscribeEvent((event) async {
      switch (event.code) {
        case 'webViewReady': _webViewReady(); break;
        case 'syncGlobals': _syncGlobals(event); break;
      }
    });
  }

  void init(BuildContext context) async {
    ...
    _prefs = await SharedPreferences.getInstance();
    _syncData = jsonDecode(_prefs.getString('globals'));
    Bridge().syncGlobals(jsonEncode(_syncData));
  }

  void update() async {
    String json = jsonEncode(_syncData);
    Bridge().syncGlobals(json);
    _prefs.setString('globals', json);
  }

  Map<String, dynamic> getData() {
    return _syncData;
  }

  void _webViewReady() {
    Bridge().syncGlobals(jsonEncode(_syncData));
  }

  void _syncGlobals(EventData event) {
    _syncData = event.params;
  }

  var _prefs;
  var _syncData = <String, dynamic>{};
}