플러터훅은 플러터 상태관리 라이브러리인 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 라이프사이클 메소드가 필요 없어졌다.