Flutter Hooks — A new beginning
Are you a fresher / beginner to flutter course or not aware of usage of hooks in flutter apps.
If yes this blog is for you, can get the in depth knowledge in usage of hooks in your flutter apps.
Hooks concept was used mostly in react app’s but now is being used in flutter apps too so why late let’s get started to the course.
Hooks are used to handle the life-cycle of a widget much easily than before. In app development you need to make use of life-cycle to make a error/crash free app.
Handling these life-cycle of a widget is not easy every time and not only this hooks reduce the usage of code multiple times and even avoid a lot of boilerplate code.
Introductory video on flutter hooks.
useState() :
You might have gone through the basic flutter app which provides a counter example.
Where you will be using StatefulWidget to handle the state of the app on every increment or decrement in the count.
With the help of the useState() flutter hook you can easily handle this scenario and that too without StatefulWidget usage.
useEffect() :
useEffect hook is called synchronously called on every build and implicitly you can call it when there is any change in the key specified.
This hook accepts a set of keys which let’s you run the functionality every time the keys provided is updated.
Can see a sample usage of useEffect()
useEffect((){
final timer = Timer.periodic(Duration(seconds: 1), (timer) { _count.value = timer.tick;
});
return timer.cancel;
},[]);
Complete implementation of useState() and useEffect() with source code.