The life cycle management of flutter is not as strong as that of Vue, React front-end frameworks. It is only init, Dispose, didupDateWidgets, not watches, or React hooks.

I’ve been wondering if I could use hooks in my flutter? Until today I stumbled upon a project: Flutter_hooks.

Try useState and useEffect first:

import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter/material.dart'; Class UseStateDemo extends HookWidget {// Note that it needs to be used in HookWidget! @override Widget build(BuildContext context) {// TODO: implement build // Final Counter = useState(0); useEffect(() { print('learn hooks : ${counter.value}'); }, [counter.value]); / / here need to monitor the change of the value of the specific return Container (child: Row (mainAxisAlignment: mainAxisAlignment spaceBetween, children: [ Text('counter: ${counter.value}'), MaterialButton( onPressed: () => counter.value++, child: Text( 'counter +' ), ) ], ), ); }}Copy the code

Next, create the simplest custom Hooks:

import 'package:flutter_hooks/flutter_hooks.dart';


void customHooks () {
  useEffect(() {
    print('custom hooks !');
  }, []);
}
Copy the code

Add custom hooks to the code above:

. import 'customHooks.dart'; class UseStateDemo extends HookWidget { @override Widget build(BuildContext context) { ... customHooks(); . }}Copy the code

Click Counter +: Output:

flutter: learn hooks : 0
flutter: custom hooks !
flutter: learn hooks : 1
flutter: learn hooks : 2
Copy the code