user_data.dart 1.21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';
import 'dart:io';
import 'dart:async';

import 'package:path/path.dart' as path;

import 'main.dart';
12
import 'package:flutter/services.dart';
13 14 15 16 17 18 19 20 21 22 23

String cachedDataFilePath = null;

Future<String> dataFilePath() async {
  if (cachedDataFilePath == null) {
    String dataDir = await getFilesDir();
    cachedDataFilePath = path.join(dataDir, 'data.json');
  }
  return cachedDataFilePath;
}

24
Future<UserData> loadFitnessData() async {
25 26 27
  String dataPath = await dataFilePath();
  print("Loading from $dataPath");
  JsonDecoder decoder = new JsonDecoder();
28
  Map data = await decoder.convert(await new File(dataPath).readAsString());
29
  return new UserDataImpl.fromJson(data);
30 31 32
}

// Intentionally synchronous for execution just before shutdown.
33
Future saveFitnessData(UserDataImpl data) async {
34 35 36 37 38 39 40
  String dataPath = await dataFilePath();
  print("Saving to $dataPath");
  JsonEncoder encoder = new JsonEncoder();
  String contents = await encoder.convert(data);
  File dataFile = await new File(dataPath).writeAsString(contents);
  print("Success! $dataFile");
}