hstate 0.1.0 copy "hstate: ^0.1.0" to clipboard
hstate: ^0.1.0 copied to clipboard

A simple state management library.

example/example.md

hstate #

example #

import 'package:flutter/material.dart';
import 'package:hstate/hstate.dart';

void main() => runApp(CounterApp());

// 1. init observable data anywhere, example the data layer
var counter = Observer(0);

class CounterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          // 2. build widget from data
          child: counter.build((value) => Text(value.toString(), textAlign: TextAlign.center)),
        ),
        floatingActionButton: FloatingActionButton(onPressed: () {
          // 3. update value & notify change
          counter.value++;
          counter.notify();
        }),
      ),
    );
  }
}

computed #

import 'package:flutter/material.dart';
import 'package:hstate/hstate.dart';

void main() => runApp(CounterApp());

var counter = Counter(0);
var counterDouble = DoubleCounter(counter);
var counterSum = SumCounter(counter, counterDouble);

class CounterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            counter.build((value) => Text(value.toString())),
            counterDouble.build((value) => Text(value.toString())),
            counterSum.build((value) => Text(value.toString())),
          ],
        ),
        floatingActionButton: FloatingActionButton(onPressed: () {
          counter.value++;
          counter.notify();
        }),
      ),
    );
  }
}

class Counter extends Observer {
  Counter(value) : super(value);

  void add(int value) {
    this.value += value;
    notify();
  }
}

class DoubleCounter extends Observer {
  final Counter counter;

  DoubleCounter(this.counter) : super(counter.value * 2) {
    counter.onWatch(update);
  }

  void update(value) {
    this.value = value * 2;
    notify();
  }
}

class SumCounter extends Observer {
  final Counter counter;
  final DoubleCounter doubleCounter;

  SumCounter(this.counter, this.doubleCounter) : super(counter.value + doubleCounter.value) {
    counter.onWatch(update);
    doubleCounter.onWatch(update);
  }

  void update(value) {
    this.value = counter.value + doubleCounter.value;
    notify();
  }
}

0
likes
130
points
19
downloads

Publisher

unverified uploader

Weekly Downloads

A simple state management library.

Documentation

API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on hstate