flhooks 1.3.0

  • Readme
  • Changelog
  • Installing
  • 67

Build Status codecov

flhooks #

Write stateful functional Component in Flutter. React like Hooks implementation for Flutter.

This package is inspired by React Hooks.

Why Hooks #

Like for React, Hooks try to be a simple method to share stateful logic between Component.

The goal of thi library is to devoid class extensions and mixin. Of course flutter is not designed for functional Component and Hooks.

Getting Started #

You should ensure that you add the flhooks as a dependency in your flutter project.

dependencies:
 flhooks: "^1.1.0"

You should then run flutter packages upgrade or update your packages in IntelliJ.

Rules #

When using Hooks, React Hooks rules must be followed.

Only Call Hooks at the Top Level #

Don’t call Hooks inside loops, conditions, or nested functions. Hooks can only be used inside a HookBuilder builder param. They can also be used to create other hooks.

Simple Usage #

Hooks can only be used inside the builder of an HookBuilder.

HookBuilder is like a StatefulBuilder how build the builder function. Hooks function can be used only in the builder function.

// Define a Slider Page
final SliderPage = () =>
    HookBuilder(
      builder: (BuildContext context) {
        // define a state of type double
        final example = useState(0.0);
        final onChanged = useCallback((double newValue) {
          // change example.value for update the value in state
          example.value = newValue;
        }, [example]);
        return Material(
          child: Center(
            child: Slider(
              key: sliderKey,
              value: example.value,
              onChanged: onChanged,
            ),
          ),
        );
      },
    );
// Start the app
void main() =>
    runApp(MaterialApp(
      home: SliderPage(),
    ));

Hooks #

Currently implemented Hooks.

useMemo #

useMemo return the memoized result of the call to fn.

fn will be recalled only if store change.

 final helloMessage = useMemo(() => 'Hello ${name}', [name]);

useCallback #

useCallback return the first reference to fn.

fn reference will change only if store change.

final onClick = useCallback(() => showAwesomeMessage(input1, input2),
  [input1, input2]);

It's the same as passing () => fn to useMemo.

useState #

useState return a StateController, HookState.value is the initial value passed to useState, or the last set using state.value = newValue.

state.value = newValue will trigger the rebuild of the StatefulBuilder.

final name = useState('');
// ... get the value
  Text(name.value);
//... update the value and rebuild the component
  onChange: (newValue) => name.value = newValue;

useEffect #

useEffect exec fn at first call or if store change. If fn return a function, this will be called if store change or when the widget dispose.

useEffect(() {
  final pub = stream.listen(callback);
  return () => pub.cancel();
  }, [stream]);

useEffect is useful for handle async or stream subscription.

Custom Hooks #

Custom Hooks function can be created composing other hooks function.

Custom Hooks name must start with 'use'.

V useAsync<V>(Future<V> Function() asyncFn, V initial, List store) {
  final state = useState(initial);
  useEffect(() {
    var active = true;
    asyncFn().then((result) {
      if (active) {
        state.value = result;
      }
    });
    return () {
      active = false;
    };
  }, store);
  return state.value;
}

Now you can use useAsync like any other hooks function.

Hot Reload #

Hot reload is basically supported.

When the hock type change, because an hook function is added, removed, or change type, the hook will be disposed and reset to null.

However after an add or a remove, all hooks after the one how change, can be disposed or had a reset.

Pay attention, will be no break after hot reloading the app, but will be other side effects.

We decide to not make hooks shift to the next position, because we prefer to have the same behavior in the case you add, remove, or change an hook function call.

Feel free to open a issue or fork the repository to suggest a new implementation.

Example #

More example in the example directory.

Changelog #

Current version is 1.1.0, read the changelog for more info.

Next on flhooks #

New hooks will be added in future like useFuture (or useAsync) and useStream, there will be no need to use FutureBuilder and StreamBuilder anymore.

We are actually testing some useIf conditional implementation of hooks.

[1.3.0] - 03/07/2019

  • added useContext

    Added the useContext hook to use the BuildContext inside other hooks

  • added HookWidget

    Added the HookWidget class to use class Widget with hooks. HookWidget is now use as the base for the HookBuilder class.

[1.1.0] - 05/01/2019

There is a lot of change in this version. This is not a major release because there are no change in the design or new functionality, excluding hot reload support (but yes, something will break updating to the new version).

This is a better implementation how make more clear the goal to avoid the use of classes and mixin and prefer instead hook functions and composition.

The change came also from the necessity to make a better division of responsibility.

  • removed Hook.dispose.

    Logic moved to a new _DisposableController, how is private, because we don't want developers use class extension or mixin. Sorry if someone was using Hook.dispose compose using useEffect instead.

  • replaced HookState with StateController

    It's a better name, and describe better the returned value of useState.

  • deprecated HookState.set (now StateController.set), use StateController.value = newValue instead

  • useState now return StateController instead of 'HookState'

  • useMemo now implements the dispose lifecycle

  • useEffect --like all the hooks functions-- use useMemo

  • added hot reload support

    When the hock type change, because an hook function is added, removed, or change type, the hook will be disposed and reset to null. There will be no break hot reloading the app. But will be other side effects.

    We decide to not make hooks shift to the next position, because we prefer to have the same behavior in the case you add, remove, or change an hook function call.

  • Added Hot Reload test

  • Added Hot Reload and Changelog section to README

We are also thinking to make use private. Everything can be done using useMemo now.

[1.0.1] - 26/12/2018

  • flutter packages get error fix

[1.0.0] - 26/12/2018

[0.0.2] - 25/12/2018

  • added useEffect hook function
  • better dartdoc comment
  • better readme
  • added travis integration
  • added test for useEffect
  • added test for hooks function scope

[0.0.1] - 23/12/2018

  • Initial Release

Use this package as a library

1. Depend on it

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


dependencies:
  flhooks: ^1.3.0

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:flhooks/flhooks.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
38
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
67
Learn more about scoring.

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

  • Dart: 2.6.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.6

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/flhooks.dart.

Run flutter format to format lib/flhooks.dart.

Maintenance suggestions

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package.

Common filename patterns include main.dart, example.dart, and flhooks.dart. Packages with multiple examples should provide example/README.md.

For more information see the pub package layout conventions.

Dependencies

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