Search code snippets, questions, articles...

Store with Flux pattern

import 'dart:convert';
import 'package:localstorage/localstorage.dart';
import 'EventManager.dart';

class TopicStore {
  final LocalStorage storage = new LocalStorage('settings.json');
  final String storeKey = "NEWS_TOPICS";
  List newsTopics = new List();

  static TopicStore instance = new TopicStore._();

  TopicStore._() {
    //initalizeTopics();
  }

  init() async {
    await _loadFromStore();
  }

  _loadFromStore() async {
    await storage.ready;
    var data = storage.getItem(storeKey);
    if (data != null) {
      newsTopics = jsonDecode(data);
      print("From Topic store .. " + newsTopics.toString());
      EventManager.eventBus.fire(new TopicEvent("loaded", newsTopics));
    }
  }

  _saveToStorage() {
    storage.setItem(storeKey, jsonEncode(newsTopics));
    EventManager.eventBus.fire(new TopicEvent("updated", newsTopics));
  }

  addTopic(String topic) {
    newsTopics.add(topic);
    _saveToStorage();
  }

  removeTopic(int index) {
    newsTopics.removeAt(index);
    _saveToStorage();
  }
}

class TopicEvent {
  String action;
  List topics;
  TopicEvent(this.action, this.topics);
}

import 'package:event_bus/event_bus.dart';

class EventManager {
  static final EventBus eventBus = EventBus();
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.
Was this helpful?
0 Comments