Skip to content

Instantly share code, notes, and snippets.

@nerdsupremacist
Created October 14, 2018 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerdsupremacist/6b268279fbd5ae7c4fc3170f255e819b to your computer and use it in GitHub Desktop.
Save nerdsupremacist/6b268279fbd5ae7c4fc3170f255e819b to your computer and use it in GitHub Desktop.
Property class for MVVM in Flutter
import 'dart:async';
import 'package:flutter/material.dart';
class Property<Value> implements Sink<Value> {
Value _internalValue;
final StreamController<Value> _streamController = StreamController.broadcast();
Value get value {
return _internalValue;
}
set value(Value newValue) {
add(newValue);
}
Stream<Value> get stream {
return _streamController.stream;
}
Property(this._internalValue);
@override
void add(Value event) {
_internalValue = event;
_streamController.add(event);
}
Widget build<V extends Widget>(V transform(Value)) {
StreamBuilder<Value> builder = new StreamBuilder(
stream: stream,
builder: (context, snapshot) {
return transform(this.value);
}
);
return builder;
}
Property<S> map<S>(S convert(Value event)) {
var property = Property(convert(value));
stream.listen((value) => property.value = convert(value));
return property;
}
void close() {
_streamController.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment