플러터훅은 플러터 상태관리 라이브러리인 riverpod을 만든 사람이 만든 라이브러리이다.
StatelessWidget
과 StatefulWidget
을 대신하는 HookWidget
을 제공하는 라이브러리이다.
StatefulWidget
은 initState
나 dispose
라는 논리를 다시 사용하기에 어렵다.예를들면, AnimationController를 사용하려는 모든 위젯을 모든 논리를 처음부터 다시 구현해야 한다.
class Example extends StatefulWidget {
final Duration duration;
const Example({Key? key, required this.duration})
: super(key: key);
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> with SingleTickerProviderStateMixin {
AnimationController? _controller;
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: widget.duration);
}
void didUpdateWidget(Example oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.duration != oldWidget.duration) {
_controller!.duration = widget.duration;
}
}
void dispose() {
_controller!.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Container();
}
}
위의 예제를 Hooks
를 이용해 다시 짠 것
class Example extends HookWidget {
const Example({Key? key, required this.duration})
: super(key: key);
final Duration duration;
Widget build(BuildContext context) {
final controller = useAnimationController(duration: duration);
return Container();
}
}
Hooks
는 widget과 완전히 독립적으로 재사용이 가능하다.
StatelessWidget
와 StatelessWidget
를 HookWidget
으로 변경import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter/material.dart';
class App extends HookWidget {
const App({super.key});
Widget build(BuildContext context) {}
StatefulWidget
을 HookWidget
으로 바꿈으로써 StatefulWidget
과 State
로 나누어진 보일러플레이트 코드와 initState
, dispose
라이프사이클 메소드가 필요 없어졌다.