Coder Social home page Coder Social logo

leocavalcante / flutter-redurx Goto Github PK

View Code? Open in Web Editor NEW
25.0 4.0 6.0 133 KB

๐ŸŽฏ Flutter bindings for ReduRx.

License: BSD 3-Clause "New" or "Revised" License

Dart 90.63% Java 3.15% Objective-C 6.22%
dart flutter redux state-management

flutter-redurx's Introduction

Please, check out: https://github.com/leocavalcante/observable_state

Flutter-ReduRx Build Status

Flutter bindings for ReduRx.

It provides a Provider as an InheritedWidget so you can reach the ReduRx Store wherever you have a BuildContext.
It also has a Connect Widget so you can grab a few parts of the State (sub-state/props) and it will automatically recall builder whenever only this little connected part of the State has changed preventing unnecessary rebuilds.

Getting started

API

Connect

  • convert: State -> Props - A function used by map to transform the state in a sub-state/props.
  • where: Props oldProps, Props newProps -> bool - A function to explicitly filter when the builder should be called.
  • builder: Props newProps -> Widget - A function that receives the sub-state/props and returns a Widget.
Connect<State, String>(
  convert: (state) => state.title,
  where: (oldTitle, newTitle) => newTitle != oldTitle,
  builder: (title) => Text(title),
)

Example

class Example1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Connect<AppState, String>(
            convert: (state) => state.title,
            where: (prev, next) => next != prev,
            builder: (title) {
              print('Building title: $title');
              return Text(title);
            },
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('You have pushed the button this many times:'),
              Connect<AppState, String>(
                convert: (state) => state.count.toString(),
                where: (prev, next) => next != prev,
                builder: (count) {
                  print('Building counter: $count');
                  return Text(count,
                      style: Theme.of(context).textTheme.display1);
                },
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => Provider.dispatch<AppState>(context, Increment()),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ));
  }
}

Handling null values

By default, Connect will only call builder if the props aren't null, otherwise it renders an empty Container. If you want to handle null values by youself, set the nullable property to true:

Connect<State, String>(
  convert: (state) => state.title,
  where: (oldTitle, newTitle) => newTitle != oldTitle,
  builder: (title) => Text(title),
  nullable: true,
)

ConnectWidget

Behaves just like Connect but is extendable. Very useful when you see yourself in a Widget with a lot of Connects.

Example

class _Props {
  _Props({
    @required this.title,
    @required this.count,
  });

  final String title;
  final String count;
}

class Example2 extends ConnectWidget<AppState, _Props> {
  @override
  _Props convert(AppState state) {
    return _Props(title: state.title, count: state.count.toString());
  }

  @override
  Widget build(BuildContext context, _Props props) {
    return Scaffold(
      appBar: AppBar(title: Text(props.title)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Text(props.count, style: Theme.of(context).textTheme.display1),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => dispatch(context, Increment()),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Provider

  • store - A ReduRx Store.
  • child - Your application's Widget.
  • static dispatch<S>(BuildContext, ActionType) - Helper to call dispatch on the Provider's context Store.
Provider(
  store: Store<State>(State('Initial title')),
  child: App(),
)
Provider.dispatch<State>(context, ChangeTitle('New title'));

For a better understanding of dispatch and ActionType head to ReduRx.

Example

import 'package:flutter/material.dart' hide State;
import 'package:flutter_redurx/flutter_redurx.dart';

class State {
  State({this.title, this.count});
  final String title;
  final int count;
}

class Increment extends Action<State> {
  @override
  State reduce(State state) =>
      State(title: state.title, count: state.count + 1);
}

void main() {
  final store =
      Store<State>(State(title: 'Flutter-ReduRx Demo Title', count: 0));
  runApp(Provider(store: store, child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter-ReduRx Demo',
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Connect<State, String>(
            convert: (state) => state.title,
            where: (prev, next) => next != prev,
            builder: (title) => Text(title ?? ''),
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('You have pushed the button this many times:'),
              Connect<State, String>(
                convert: (state) => state.count.toString(),
                where: (prev, next) => next != prev,
                builder: (count) => Text(count ?? '',
                    style: Theme.of(context).textTheme.display1),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => Provider.dispatch<State>(context, Increment()),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ));
  }
}

flutter-redurx's People

Contributors

leocavalcante avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

flutter-redurx's Issues

Default widget builder returns Container()

Hi,

The default widget builder for ReduRx returns a Container() for null data - this causes two problems:

  1. Sometimes Flutter expects a RenderSliver instead of a RenderBox, so this implementation throws a framework error when the appropriate 'empty' widget should be SliverFillRemaining();

  2. Returning Container() assumes that the developer doesn't want to use null as a check for other build logic.

Would it be possible to make the following change?

@override Widget build(BuildContext context) { return StreamBuilder<P>( stream: _stream, builder: (context, snapshot) { if (snapshot.data == null && !nullable) { return Container(); } _prev = snapshot.data; return builder(_prev); }, ); }

====>

@override Widget build(BuildContext context) { return StreamBuilder<P>( stream: _stream, builder: (context, snapshot) { _prev = snapshot.data; return builder(_prev); }, ); }

`AsyncAction` bug

Dispatch an AsyncAction invokes the middleware's beforeAction method twice.I tweak a little on your example:

import 'dart:async';

import 'package:flutter/material.dart' hide State;
import 'package:flutter_redurx/flutter_redurx.dart';

class State {
  State({this.title, this.count});
  final String title;
  final int count;
}

/***************** tweaked ****************/
class Increment extends AsyncAction<State> {
  @override
  Future<Computation<State>> reduce(State state) async {
    print('in action: Increment: $state');
    return (State state) => State(title: state.title, count: state.count + 1);
  }
}
/***************** tweaked ****************/

void main() {
  /***************** tweaked ****************/
  final store =
      Store<State>(State(title: 'Flutter-ReduRx Demo Title', count: 0))
          .add(LogMiddleware());
  /***************** tweaked ****************/
  runApp(Provider(store: store, child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter-ReduRx Demo',
      theme: ThemeData(primarySwatch: Colors.pink),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Connect<State, String>(
          convert: (state) => state.title,
          where: (prev, next) => next != prev,
          builder: (title) {
            print('Building title: $title');
            return Text(title);
          },
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Connect<State, String>(
              convert: (state) => state.count.toString(),
              where: (prev, next) => next != prev,
              builder: (count) {
                print('Building counter: $count');
                return Text(count, style: Theme.of(context).textTheme.display1);
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => Provider.dispatch<State>(context, Increment()),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

This will output

12:40:44.015 1 info flutter.tools flutter: Before action: Increment: Instance of 'State'
12:40:44.015 2 info flutter.tools flutter: in action: Increment: Instance of 'State'
12:40:44.015 3 info flutter.tools flutter: Before action: Increment: Instance of 'State'
12:40:44.015 4 info flutter.tools flutter: After action: Increment: Instance of 'State'
12:40:44.038 5 info flutter.tools flutter: Building counter: 1

Unable to respond to null to non-null state changes and vice versa

On this line it seems that a builder won't be invoked if the sub-state we're monitoring from a widget is null:

return Container();

Here's my use case:

  • I have a widget representing some object in a list of objects
  • When the user touches down, I change a field highlightedObject in the app state via Action dispatch to match the object represented by the item
  • I then want my widget to rebuild with a different visual style if the object it represents matches the highlightedObject in the app state, so I've wrapped it in a Connector that converts using the state's highlightedObject

And what happens:

  • The initial highlightedObject is null, so the Connector for my object widget doesn't call the builder I provided โ€” so no widgets in my list are shown

Is this by design? Thanks!

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.