Created
October 14, 2018 03:20
-
-
Save nerdsupremacist/6b268279fbd5ae7c4fc3170f255e819b to your computer and use it in GitHub Desktop.
Property class for MVVM in Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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