Skip to content

Instantly share code, notes, and snippets.

@nabe33
Created March 23, 2024 08:19
Show Gist options
  • Save nabe33/9025ae334c99e8e5a8ec85ff9ac12049 to your computer and use it in GitHub Desktop.
Save nabe33/9025ae334c99e8e5a8ec85ff9ac12049 to your computer and use it in GitHub Desktop.
HooksとRiverpodを使う例
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final counterProvider = StateProvider<int>((ref) => 0);
void main() {
runApp(
ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(
title: Text('HookConsumerWidget Example'),
),
body: Center(
child: Text('Counter: $counter', style: TextStyle(fontSize: 20)),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).state++,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment