flutter中的生命週期管理相對沒有Vue、react這種前端框架強,只有init
、dispose
、didUpdateWidget
,沒有類似vue中watch這種,或是react hooks。
我一直在想能否在flutter中使用hooks?直到今天偶然間發現一個專案:flutter_hooks.
先嚐試一下useState
和useEffect
:
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter/material.dart';
class UseStateDemo extends HookWidget {
// 注意需要在HookWidget中使用 !
@override
Widget build(BuildContext context) {
// TODO: implement build
// 這裡和react的寫法略有不同
final counter = useState(0);
useEffect(() {
print('learn hooks : ${counter.value}');
}, [counter.value]); // 這裡需要監控到具體的值的變化
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('counter: ${counter.value}'),
MaterialButton(
onPressed: () => counter.value++,
child: Text(
'counter +'
),
)
],
),
);
}
}
複製程式碼
接下來建一個最簡單custom Hooks:
import 'package:flutter_hooks/flutter_hooks.dart';
void customHooks () {
useEffect(() {
print('custom hooks !');
}, []);
}
複製程式碼
在上面的程式碼中加入custom hooks:
...
import 'customHooks.dart';
class UseStateDemo extends HookWidget {
@override
Widget build(BuildContext context) {
...
customHooks();
...
}
}
複製程式碼
點選counter +
:
輸出:
flutter: learn hooks : 0
flutter: custom hooks !
flutter: learn hooks : 1
flutter: learn hooks : 2
複製程式碼