GithubHelp home page GithubHelp logo

allasca / flutter_reactive_value Goto Github PK

View Code? Open in Web Editor NEW

This project forked from lukehutch/flutter_reactive_value

0.0 0.0 0.0 305 KB

Ultra-simple state management and reactivity for Flutter UIs

License: Other

Ruby 4.70% C++ 36.62% C 2.50% Objective-C 0.07% Kotlin 0.22% Dart 17.75% Swift 2.27% HTML 3.18% CMake 32.70%

flutter_reactive_value's Introduction

The flutter_reactive_value library

This library provides a mechanism for causing a UI to reactively update in response to changes in underlying values in your data model.

This is the simplest possible state management / reactive UI update solution for Flutter, by far, reducing boilerplate compared to all the other insanely complex state management approaches currently available.

The closest thing to flutter_reactive_value is ValueListenableBuilder. flutter_reactive_value provides the same basic capabilities as ValueListenableBuilder, but with much less syntactic overhead (i.e. you could think of flutter_reactive_value as syntactic sugar). ValueListenableBuilder may work better if your reactive widget has a child element that is complex and non-reactive, because it takes a child parameter for any child widget that is not affected by changes to the ValueNotifier's value.

Usage

(1) Add a dependency upon flutter_reactive_value in your pubspec.yaml (replace any with the latest version, if you want to control the version), then run flutter pub get:

dependencies:
  flutter:
    sdk: flutter
  flutter_reactive_value: any

(2) Import the package in your Flutter project:

import 'package:flutter_reactive_value/flutter_reactive_value.dart'

(3) Use ReactiveValueNotifier<T> rather than the standard Flutter ValueNotifier<T> to declare any values you want your UI to listen for changes to:

final counter = ReactiveValueNotifier(0);

(4) Build your UI the standard way, using a Widget hierarchy, and anywhere you want to use the value and respond to future changes in the value by updating the UI, instead of using the usual ValueNotifier.value getter method, use ReactiveValueNotifier.reactiveValue(BuildContext):

class HomeView extends StatelessWidget {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          // Read value, and subscribe to changes:
          'The count is: ${counter.reactiveValue(context)}',
          style: const TextStyle(fontSize: 20),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Update value:
          counter.value++;
        },
        tooltip: 'Increment',
        child: const Icon(Icons.plus_one_outlined),
      ),
    );
  }
}

Now whenever counter.value changes (here using counter.value++ in the onPressed handler), the enclosing widget (here HomeView), from which the BuildContext was obtained, will be scheduled for rebuilding.

(The only place you're not allowed to update counter.value is the build method of a widget, since state changes are disallowed in build methods.)

There is no need to dispose the ValueNotifier listener -- it is automatically removed whenever the value changes (and it is added back whenever the build method is called, during a rebuild).

That's all there is to it, at least for simple usage!

Optimizing UI updates

If you have a deep nested tree of Widget constructor calls within a single StatelessWidget or StatefulWidget, then you probably don't want to rebuild the whole Widget subtree each time only one value changes. You can limit the region that is updated by using Builder to introduce a new BuildContext right above the reactiveValue(context) call.

Before:

// ...
Container(
  child: Text('${counter.reactiveValue(context)}'),
),
// ...

After:

// ...
Container(
  child: Builder(
    builder: (subContext) => Text('${counter.reactiveValue(subContext)}'),
  ),
),
// ...

Notifying listeners of deeper changes

If you try to wrap a collection or object in a ValueNotifier, e.g. to track a set of values using ValueNotifier<Set<T>>, then modifying fields, or adding or removing values from the collection or object will not notify the listeners of the ValueNotifier that the value has changed (because the value itself has not changed). In this case you can call the extension method notifyChanged() to manually call the listeners. For example:

final tags = ReactiveValueNotifier(<String>{});

void addOrRemoveTag(String tag, bool add) {
  if ((add && tags.value.add(tag)) || (!add && tags.value.remove(tag))) {
    tags.notifyChanged();
  }
}

Pro-tip: persistence

See my other library, flutter_persistent_value_notifier, to enable persistent state in your app!

Author

flutter_reactive_value was written by Luke Hutchison, and is released under the MIT license.

flutter_reactive_value's People

Contributors

lukehutch avatar aturex1 avatar allasca avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.