일반적인 함수처럼 사용됩니다. 아래와 같이 메서드를 인자로 받아 사용합니다.
useCallback(T callback, [List<Object?> keys = const <Object>[]])
a와 b의 값을 각각 증가시켜 합을 반환하는 useCallback을 사용한 sumATOB 예시입니다.
class UsecallbackEx extends HookWidget {
const UsecallbackEx({super.key});
Widget build(BuildContext context) {
var a = useState(0);
var b = useState(0);
var sumATOB = useCallback((a, b) {
return a + b;
}, [a, b]);
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(sumATOB(a.value, b.value).toString()),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
a.value++;
},
child: const Text('a')),
ElevatedButton(
onPressed: () {
b.value++;
},
child: const Text('b')),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(a.value.toString()),
const SizedBox(width: 60),
Text(b.value.toString()),
],
)
],
),
)),
);
}
}