global_state_hook 0.0.2 copy "global_state_hook: ^0.0.2" to clipboard
global_state_hook: ^0.0.2 copied to clipboard

Global state in one line (not 5 files)

Synchronize global state with one hook.

Motivation #

I found myself creating a lot of boilerplate to manage simple global state values. I want to be able to create a global state value with a single line of code. I did not want to create a whole new class like ChangeNotifier and especially not Bloc or Cubit.

Getting started #

  • Add flutter_hooks.
    • flutter pub add flutter_hooks
  • Add global_state_hook.'
    • flutter pub add global_state_hook

Initialize #

import 'package:global_state_hook/global_state_hook.dart';

await GlobalStateHook.init();

This is required because the package uses shared_preferences to optionally persist the state.

Basic usage #

// Don't forget to use HookWidget
class SomeWidgetA extends HookWidget {
  const SomeWidgetA({super.key});

  @override
  Widget build(BuildContext context) {
    final someGlobalState = useGlobalState<int>('some-key', 0);

    return Column(
      children: [
        Text('Value in A: ${someGlobalState.value}'),
        ElevatedButton(
          onPressed: () => someGlobalState.value++,
          child: Text('Increment'),
        )
      ],
    );
  }
}

class SomeWidgetB extends HookWidget {
  const SomeWidgetB({super.key});

  @override
  Widget build(BuildContext context) {
    final someGlobalState = useGlobalState<int>('some-key', 0);

    return Column(
      children: [
        Text('Value in B: ${someGlobalState.value}'),
        ElevatedButton(
          onPressed: () => someGlobalState.value++,
          child: Text('Increment'),
        )
      ],
    );
  }
}

Tip #

// To avoid bugs with mismatched keys and types, 
// you can wrap the global hook in another hook
GlobalHookResult<int> useMyGlobalState() => useGlobalState<int>('unique-key', 0);

Persistence #

You can persist the state in shared preferences. The shared preferences key will be the same as the global state key.

final persistedGlobalValue = useGlobalState<int>('some-key', 0, persisted: true);

For complex objects, you'll need to add a serializer and deserializer.

final persistedGlobalObjectValue = useGlobalState<MyClass>('some-key', MyClass(), persisted: true, MyClass.serializer);

// Which must implement
abstract class Serializer<T> {
  abstract final T Function(String str) deserialize;
  abstract final String Function(T value) serialize;
}

I don't like this api, might change it in the future.

1
likes
130
points
93
downloads

Publisher

unverified uploader

Weekly Downloads

Global state in one line (not 5 files)

Repository (GitHub)

Documentation

API reference

License

MIT (license)

Dependencies

flutter, flutter_hooks, shared_preferences

More

Packages that depend on global_state_hook