flutter_simple_state 0.5.1+2

  • Readme
  • Changelog
  • Example
  • Installing
  • 72

flutter_simple_state #

Pub Build Status

Easy to understand state management for Flutter apps and for writing reusable Flutter components:

  • Events are handled using callbacks/functions.
    • Nothing to learn: Simple concept that everybody knows.
    • Easy to debug/understand: Use "jump to definition" to see what the code does.
    • Good for reusable components: Callbacks work well with any app architecture (BLoC, Stream, etc.).
  • State is held in one or multiple instances of ValueNotifier/ValueListenable.
    • Nothing to learn: Standard Flutter classes that are widely in use and that everybody knows.
    • You always have access to the current value (better than working with streams).
  • AutoRebuild automatically rebuilds your widgets when a ValueNotifier (or actually, any Listenable) triggers a notification.
    • Tracks all ValueListenable/Listenable objects for you, so you don't have to call addListener/removeListener.
    • Provides fine-grained control for minimizing amount of redraws (more fine-grained than InheritedWidget).
    • Standard Flutter classes like TextEditingController and Animation implement ValueListenable and thus work nicely with AutoRebuild.
  • No indirection and no boilerplate (e.g. compared to BLoC or Redux).
    • No custom event objects.
    • No event handlers with long switch() statements.
    • No streams, no ugly StreamBuilder.
    • Only small, trivial code that everyone can understand and debug with ease.

Usage #

A simple AutoRebuild example:

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

class MyPage extends StatelessWidget {
  MyPage({Key key, @required this.counter}) : super(key: key);

  final ValueNotifier<int> counter;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Counter')),
      body: Column(
        children: <Widget>[
          AutoRebuild(builder: (context, get, track) {
            return Text('Counter: ${get(counter)}');
          }),
          MaterialButton(
            onPressed: () => counter.value++,
            child: Text('Increment'),
          ),
        ],
      ),
    );
  }
}

Also, take a look at the example in the repo. It shows everything you need to know.

As a rule of thumb, try to avoid global state because that can make your code too tightly coupled and at some point turn into a monolithic mess. Imagine your app as a tree of pages (and each page as a tree of widgets) and think about which page depends on which state/action: Put the state/action as deeply nested (close to the leafs) in the tree as possible. Use arguments instead of Provider if that's convenient enough. Only use global state if every part of your app depends on it (e.g. the currently logged-in user).

Value vs ValueNotifier #

As an alternative to ValueNotifier you can also use flutter_simple_state's Value class which provides an update() method for modifying more complex objects:

class User {
  String name = '';
  String email = '';
  // ...
}

var userValue = Value(User());
userValue.update((user) {
  user.name = 'Adam';
  user.email = 'adam@adam.com';
});

This is similar to calling setState() with StatefulWidget. With update() you can change multiple attributes and Value will trigger a single notification once finished - even if nothing was changed (so you don't need to implement comparison operators for complex objects).

Changelog #

[0.5.1+2]

[0.5.1+1]

  • Initial public release

example/lib/main.dart

// This is a simple, but pretty complete flutter_simple_state example.
// It demonstrates use-cases for small and large apps:
//
// Actions & state values can be globally accessible via Provider.
// This can be useful for making e.g. the currently logged-in user accessible
// from anywhere in the app.
//
// Actions & state values can alternatively be passed directly as arguments.
// This is important for writing reusable components that mustn't depend on
// some globally accessible app-specific state.

import 'package:flutter/material.dart';
import 'package:flutter_simple_state/flutter_simple_state.dart';
import 'package:provider/provider.dart';

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

class User {
  User({this.name = '', this.email = '', this.location = ''});

  String name;
  String email;
  String location;
}

// Global state that the whole app has access to via a Provider.
// For complex apps you might want to split this up into multiple classes
// that cleanly take care of orthogonal state & action aspects.
class GlobalState {
  // We use Value instead of ValueNotifier because we need the update() helper below.
  final user = Value<User>(User());

  // A globally reachable action that is potentially used in multiple places.
  void updateUser(String name, String email) {
    // This demonstrates the Value.update() helper
    user.update((u) {
      u.name = name;
      u.email = email;
    });
  }
}

// We use a StatefulWidget to retain the state between hot reloads
class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  // Global state that will be available in the whole app.
  final state = GlobalState();

  // Local state that is only accessible to a subsection of the app.
  // If you have to pass lots of these objects as arguments *and* if they
  // conceptually belong together, you might want to group them in classes like
  // we did with GlobalState and pass a whole group as a single argument.
  final counter = ValueNotifier<int>(0);

  // A local action that is potentially used in multiple places, but only
  // needed in a subsection of your app.
  void decrement() {
    counter.value--;
  }

  @override
  Widget build(BuildContext context) {
    // We use a MultiProvider, so we can easily add more state objects later
    return MultiProvider(
      providers: [Provider.value(value: state)],
      child: MaterialApp(
        title: 'flutter_simple_state example',
        home: HomePage(counter: counter, decrement: decrement),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  HomePage({Key key, @required this.counter, @required this.decrement})
      : super(key: key);

  final ValueNotifier<int> counter;
  final VoidCallback decrement;
  final nameController = TextEditingController();
  final emailController = TextEditingController();

  void _saveUser(GlobalState globalState) {
    globalState.updateUser(nameController.text, emailController.text);
  }

  @override
  Widget build(BuildContext context) {
    final globalState = Provider.of<GlobalState>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Edit values'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Counter (press "+"/"-" buttons):'),
            // We use multiple AutoRebuild widgets to minimize redrawing.
            AutoRebuild(builder: (context, get, track) {
              return Text(
                '${get(counter)}',
                style: Theme.of(context).textTheme.display1,
              );
            }),
            SizedBox(height: 20),
            Text(
              'User data',
              style: Theme.of(context).textTheme.display1,
            ),
            AutoRebuild(builder: (context, get, track) {
              var user = get(globalState.user);
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text('Name: ${user.name}'),
                  Text('Email: ${user.email}'),
                ],
              );
            }),
            Container(
              constraints: BoxConstraints(
                  maxWidth: MediaQuery.of(context).size.width * 0.7),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  TextFormField(
                    decoration: InputDecoration(hintText: 'Name'),
                    controller: nameController,
                    textCapitalization: TextCapitalization.words,
                    keyboardType: TextInputType.text,
                  ),
                  TextFormField(
                    decoration: InputDecoration(hintText: 'Email'),
                    controller: emailController,
                    autocorrect: false,
                    keyboardType: TextInputType.emailAddress,
                  ),
                ],
              ),
            ),
            AutoRebuild(builder: (context, get, track) {
              var enabled = get(nameController).text.isNotEmpty &&
                  get(emailController).text.isNotEmpty;
              var onPressed = enabled ? () => _saveUser(globalState) : null;
              return MaterialButton(
                onPressed: onPressed,
                child: Text('Save'),
              );
            })
          ],
        ),
      ),
      floatingActionButton: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.add),
              // Demonstrating trivial update case
              onPressed: () => counter.value++,
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.remove),
              // Demonstrating reusable action via callback
              onPressed: decrement,
            ),
          ),
        ],
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_simple_state: ^0.5.1+2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_simple_state/flutter_simple_state.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
43
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
72
Learn more about scoring.

We analyzed this package on Oct 18, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/flutter_simple_state.dart.

Run flutter format to format lib/flutter_simple_state.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.4.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test