global_state_hook 0.0.2
global_state_hook: ^0.0.2 copied to clipboard
Global state in one line (not 5 files)
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:global_state_hook/global_state_hook.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true),
home: FutureBuilder(
future: () async {
// Make sure to initialize the global state before using it
return await GlobalStateHook.init();
}(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
return const HomePage();
},
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text('Global state hook demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Global state demo'),
const WidgetA(),
const WidgetB(),
const WidgetC(),
])),
);
}
}
// This could be inlined in the widget, but make sure the key is the same in the widgets that use it
GlobalHookResult<int> useGlobalValue() => useGlobalState<int>('unique-key', 0);
class WidgetA extends HookWidget {
const WidgetA({super.key});
@override
Widget build(BuildContext context) {
final globalValue = useGlobalValue();
return Column(
children: [
Text('Widget A: ${globalValue.value}'),
ElevatedButton(
onPressed: () {
globalValue.value++;
},
child: Text('Increment')),
],
);
}
}
class WidgetB extends HookWidget {
const WidgetB({super.key});
@override
Widget build(BuildContext context) {
final globalValue = useGlobalValue();
print('Widget B rebuild');
return Column(
children: [
Text('Widget B: ${globalValue.value}'),
ElevatedButton(
onPressed: () {
globalValue.value++;
},
child: Text('Increment')),
],
);
}
}
class WidgetC extends HookWidget {
const WidgetC({super.key});
@override
Widget build(BuildContext context) {
final otherValue = useGlobalState<int>('other-key', 0, persisted: true);
print('Widget C rebuild');
return Column(
children: [
Text('Widget C (persisted): ${otherValue.value}'),
ElevatedButton(
onPressed: () {
otherValue.value++;
},
child: Text('Increment')),
],
);
}
}