flutter_redux
a set of utilities that allow you to easily consume a redux store to build flutter widgets.
this package supports null-safety and is built to work with redux.dart 5.0.0+.
redux widgets
storeprovider
– the base widget. it will pass the given redux store to all descendants that request it.storebuilder
– a descendant widget that gets the store from astoreprovider
and passes it to a widgetbuilder
function.storeconnector
– a descendant widget that gets the store from the neareststoreprovider
ancestor, converts thestore
into aviewmodel
with the givenconverter
function, and passes theviewmodel
to abuilder
function. any time the store emits a change event, the widget will automatically be rebuilt. no need to manage subscriptions!
examples
- simple example – a port of the standard “counter button” example from flutter
- github search – an example of how to search as a user types, demonstrating both the middleware and epic approaches.
- todo app – a more complete example, with persistence, routing, and nested state.
- timy messenger – large open source app that uses flutter_redux together with firebase firestore.
companion libraries
- flipperkit_redux_middleware – redux inspector (use flutter debugger) for flutter redux apps
- flutter_redux_dev_tools – time travel dev tools for flutter redux apps
- redux_persist – persist redux state
- flutter_redux_navigation – use redux events for navigation
- flutter_redux_gen – vs code extension to generate redux code.
usage
let’s demo the basic usage with the all-time favorite: a counter example!
note: this example requires flutter_redux 0.4.0+ and dart 2! if you’re using
dart 1, see the old
example.
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
// one simple action: increment
enum actions { increment }
// the reducer, which takes the previous count and increments it in response
// to an increment action.
int counterreducer(int state, dynamic action) {
if (action == actions.increment) {
return state + 1;
}
return state;
}
void main() {
// create your store as a final variable in the main function or inside a
// state object. this works better with hot reload than creating it directly
// in the `build` function.
final store = store<int>(counterreducer, initialstate: 0);
runapp(flutterreduxapp(
title: 'flutter redux demo',
store: store,
));
}
class flutterreduxapp extends statelesswidget {
final store<int> store;
final string title;
flutterreduxapp({key key, this.store, this.title}) : super(key: key);
@override
widget build(buildcontext context) {
// the storeprovider should wrap your materialapp or widgetsapp. this will
// ensure all routes have access to the store.
return storeprovider<int>(
// pass the store to the storeprovider. any ancestor `storeconnector`
// widgets will find and use this value as the `store`.
store: store,
child: materialapp(
theme: themedata.dark(),
title: title,
home: scaffold(
appbar: appbar(
title: text(title),
),
body: center(
child: column(
mainaxisalignment: mainaxisalignment.center,
children: [
// connect the store to a text widget that renders the current
// count.
//
// we'll wrap the text widget in a `storeconnector` widget. the
// `storeconnector` will find the `store` from the nearest
// `storeprovider` ancestor, convert it into a string of the
// latest count, and pass that string to the `builder` function
// as the `count`.
//
// every time the button is tapped, an action is dispatched and
// run through the reducer. after the reducer updates the state,
// the widget will be automatically rebuilt with the latest
// count. no need to manually manage subscriptions or streams!
storeconnector<int, string>(
converter: (store) => store.state.tostring(),
builder: (context, count) {
return text(
'the button has been pushed this many times: $count',
style: theme.of(context).texttheme.display1,
);
},
)
],
),
),
// connect the store to a floatingactionbutton. in this case, we'll
// use the store to build a callback that will dispatch an increment
// action.
//
// then, we'll pass this callback to the button's `onpressed` handler.
floatingactionbutton: storeconnector<int, voidcallback>(
converter: (store) {
// return a `voidcallback`, which is a fancy name for a function
// with no parameters and no return value.
// it only dispatches an increment action.
return () => store.dispatch(actions.increment);
},
builder: (context, callback) {
return floatingactionbutton(
// attach the `callback` to the `onpressed` attribute
onpressed: callback,
tooltip: 'increment',
child: icon(icons.add),
);
},
),
),
),
);
}
}
purpose
one question that reasonable people might
ask:
why do you need all of this if statefulwidget
exists?
my advice is the same as the original redux.js author: if you’ve got a simple
app, use the simplest thing possible. in flutter, statefulwidget
is perfect
for a simple counter app.
however, say you have more complex app, such as an e-commerce app with a
shopping cart. the shopping cart should appear on multiple screens in your app
and should be updated by many different types of widgets on those different
screens (an “add item to cart” widget on all your product screens, “remove item
from cart” widget on the shopping cart screen, “change quantity” widgets, etc).
additionally, you definitely want to test this logic, as it’s the core business
logic to your app!
now, in this case, you could create a testable shoppingcart
class as a
singleton or create a root statefulwidget
that passes the shoppingcart
down
down down through your widget hierarchy to the “add to cart” or “remove from
cart” widgets.
singletons can be problematic for testing, and flutter doesn’t have a great
dependency injection library (such as dagger2) just yet, so i’d prefer to avoid
those.
yet passing the shoppingcart all over the place can get messy. it also means
it’s way harder to move that “add to item” button to a new location, b/c you’d
need up update the widgets throughout your app that passes the state down.
furthermore, you’d need a way to observe when the shoppingcart
changes so you
could rebuild your widgets when it does (from an “add” button to an “added”
button, as an example).
one way to handle it would be to simply setstate
every time the shoppingcart
changes in your root widget, but then your whole app below the rootwidget would
be required to rebuild as well! flutter is fast, but we should be smart about
what we ask flutter to rebuild!
therefore, redux
& redux_flutter
was born for more complex stories like this
one. it gives you a set of tools that allow your widgets to dispatch
actions
in a naive way, then write the business logic in another place that will take
those actions and update the shoppingcart
in a safe, testable way.
even more, once the shoppingcart
has been updated in the store
, the store
will emit an onchange
event. this lets you listen to store
updates and
rebuild your ui in the right places when it changes! now, you can separate your
business logic from your ui logic in a testable, observable way, without having
to wire up a bunch of stuff yourself!
similar patterns in android are the mvp pattern, or using rx observables to
manage a view’s state.
flutter_redux
simply handles passing your store
down to all of your
descendant storeconnector
widgets. if your state emits a change event, only
the storeconnector
widgets and their descendants will be automatically rebuilt
with the latest state of the store
!
this allows you to focus on what your app should look like and how it should
work without thinking about all the glue code to hook everything together!
Comments are closed.