SlideShare a Scribd company logo
Flutter Hooks
Tutorial (Part
1): Flutter
Animation
using Hooks
(useEffect and
useAnimation
Controller)
www.bacancytechnology.com
Do you remember how we used to do
programming before Flutter hooks weren’t
part of Flutter? It was a bit difficult and
overwhelming, right? Here’s a Flutter
tutorial where we will explore pre-hooks
and post-hooks Flutter life. We will learn
how to use useEffect and
useAnimationController in our demo app.
Let’s get ready and build an application,
then!
Basics of
Flutter
Animation
Animation controller
Manage animation
Listen for updates
Manipulate animation
In this Flutter Hooks tutorial, we will learn
how to install and build an animation demo
using hooks in Flutter, and also, we will look
at how we used to code before hooks
weren’t introduced. Before moving on to
the Flutter hooks tutorial, let’s discuss the
basics of animation.


We need to do the below things for
animation,




The default part is the “Animation,” There
are two types of animation that Flutter
supports.
Tween Animation– It is the short form
of in-betweening. The animation must
define the start and endpoint. The
animation will have a start value and
then reaches the end value through
various intermediate values.
Physics-based Animation– It allows you
to interact with an app more
realistically and interactively.


In simple words, an Animation controller is
called whenever its value changes,


Ticker calls tick function every frame. After
each tick, it provides a callback function
after it is started. In our case, the ticker
listener is the controller.
useEffect hook fetches data from a
server and sets the fetch to the local
state
useState hook manages local states in
apps
useMemoized hook memoizes
complicated functions to achieve
optimal app performance
useRef hook creates an object that has
one mutable property.
Flutter hooks have not received much
visibility and acknowledgment, but that
won’t make them less awesome. With the
help of the flutter_hooks library, we can
provide a robust way for managing the
lifecycle of widgets by reducing code
duplication and increasing code-sharing.


Flutter provides in-built hooks as shown
below:
useCallback hook cache a function
instance.
useContext hook obtain the
BuildContext of the building
HookWidget
useValueChanged Hook watches a value
and calls a callback whenever the value
changes.


In this guide, we’ll use the useEffect hook
for redirection after some duration, and
useAnimationController hook to create an
instance of AnimationController. Flutter,
just like ReactJS, also gives you the
opportunity of creating your custom hooks.
We will discuss that later in the tutorial.
Without further ado, let’s get started with
the Flutter hooks tutorial.
Pre-Hooks
Life:
Animation
without
Flutter Hooks
First of all, let’s see the splash screen
animation demo without implementing
flutter hooks and using the stateful widget;
it needs to be mixed in with a
TickerProviderStateMixin.


And don’t forget to dispose of the animation
controller.


class SplashScreen extends StatefulWidget {
const SplashScreen();
@override
_SplashScreenState createState() =>
_SplashScreenState();
}
class _SplashScreenState extends State
with TickerProviderStateMixin {
late AnimationController
_animationController;
late AnimationController controller;
late Animation< Offset > offset
@override
void initState() {
super.initState();
startTime();
_animationController = new
AnimationController(vsync: this, duration:
Duration(seconds: 3));
_animationController.repeat(reverse:
false);
controller = AnimationController(vsync:
this, duration: Duration(seconds: 2));
offset = Tween< Offset >(begin: Offset(0.0,
1.0), end: Offset.zero).animate(controller);
controller.forward();
}
startTime() async {
var duration = Duration(seconds: 3);
return Timer(duration, navigatePage);
}
Future navigatePage() async {
Route route = MaterialPageRoute(builder:
(context) => HomePage());
Navigator.of(context).pushReplacement(ro
ute);
}
@override
void dispose() {
_animationController.dispose();
controller.dispose();
super.dispose();
}
...
}
All of the above code is set up for
animation. And then we will just apply
these instances to our widgets/design. That
is just easy to understand.
Post-Hooks
Life:
Installation
and Flutter
Hooks
Example
How to Install Flutter hooks?
Run the following command for installing
flutter hooks
flutter pub add flutter_hooks
The command will update pubspec.yaml file
of the dependencies section with
flutter_hooks: VERSION_NUMER_HERE.


OR you can directly update pubspec.yaml
with flutter_hooks as shown below


dependencies:
flutter:
sdk: flutter
flutter_hooks:
Save the file, and Flutter will install the
dependency. Now, import the flutter_hooks
library.


import
'package:flutter_hooks/flutter_hooks.dart';
How to Implement
Animation using Flutter
Hooks?
The first change to make is to replace the
Stateful Widget with Hook Widget. And
then, to initialize the animation controllers,
we will use the useAnimationController()
method, a default method provided by the
flutter_hook library. And we can remove all
boilerplate code from initState and dispose
method.
class SplashScreen extends HookWidget {
@override
Widget build(BuildContext context) {
AnimationController
_animationController =
useAnimationController(duration:
Duration(seconds: 4), initialValue: 1);
_animationController.repeat(reverse:
false);
AnimationController controller =
useAnimationController(duration:
Duration(seconds: 3), initialValue: 1);
controller.repeat(reverse: false, period:
Duration(seconds: 4));
controller =
useAnimationController(duration:
Duration(seconds: 3), initialValue: 1);
controller.repeat(reverse: false, period:
Duration(seconds: 4));
Animation< Offset > offset = Tween< Offset
>(begin: Offset(0.0, 1.0), end:
Offset.zero).animate(controller);
controller.forward();
useEffect(() {
Timer.periodic(Duration(seconds: 4), (time)
{
Route route = MaterialPageRoute(builder:
(context) => HomePage());
Navigator.of(context).pushReplacement(ro
ute);
});
});
return SafeArea(
child: Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFFFFFFFF),
Color(0xffE3F3FF)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Stack(
children: [
FadeTransition(
opacity: _animationController,
child: Center(
child: FlutterLogo(
size: 50,
)),
),
Align(
alignment: Alignment.bottomCenter,
child: SlideTransition(
position: offset,
child: Image.asset(
'assets/images/splash_bg.png',
width: MediaQuery.of(context).size.width,
fit: BoxFit.fill,
),
))
],
),
),
));
}
}
But the problem with the above code is
there is no way to dispose the animation
controller instances; we have a solution for
this, called custom hooks.
Flutter Hooks
Tutorial to
Create
Custom
Hooks
The custom AnimationController hooks in
Flutter will instantiate an
AnimationController and return the
ScrollController to use it from the UI. It will
help in holding all the code, practically,
which was previously stored in the State
object of a StatefulWidget.


The most basic hook can be just a simple
function. Let’s create one under
hooks/controller_for_animation.dart. And
also one for Animation< Offset >.


// hooks/controller_for_animation.dart.
AnimationController
useControllerForAnimation() {
return
use(_AnimControllerForAnimationHook());
}
class _AnimControllerForAnimationHook
extends Hook {
@override
_AnimControllerForAnimationHookState
createState() =>
_AnimControllerForAnimationHookState();
}
class
_AnimControllerForAnimationHookState
extends HookState {
late AnimationController _animController;
@override
void initHook() {
_animController =
useAnimationController(duration:
Duration(seconds: 4), initialValue: 1);
_animController.repeat(reverse: false);
}
@override
AnimationController build(BuildContext
context) => _animController;
@override
void dispose() =>
_animController.dispose();
}
Animation< Offset > useOffsetHook() {
return
use(_AnimOffsetForAnimationHook());
}
class _AnimOffsetForAnimationHook
extends Hook> {
@override
_AnimOffsetForAnimationHookState
createState() =>
_AnimOffsetForAnimationHookState();
}
class _AnimOffsetForAnimationHookState
extends HookState,
_AnimOffsetForAnimationHook> {
late AnimationController _controller;
late Animation< Offset > offset;
@override
void initHook() {
_controller =
useAnimationController(duration:
Duration(seconds: 3), initialValue: 1);
_controller.repeat(reverse: false, period:
Duration(seconds: 4));
offset = Tween(begin: Offset(0.0, 1.0), end:
Offset.zero).animate(_controller);
_controller.forward();
}
@override
Animation< Offset > build(BuildContext
context) => offset;
@override
void dispose() => _controller.dispose();
}
All we did was move logic to this new class;
also, there is one dispose method from
which we can also dispose that controller,
and now simply use that
useControllerForAnimation. The method
inside build method of the splash screen.


class SplashScreen extends HookWidget {
@override
Widget build(BuildContext context) {
AnimationController
_animationController =
useControllerForAnimation();
Animation< Offset > offset =
useOffsetHook();
…….
}
Also, create one hook widget inside
hook/timer_widget.dart to redirect to a
home screen after some duration.
// hook/timer_widget.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import
'package:flutter_hooks/flutter_hooks.dart';
import
'package:flutter_hooks_demo/home_page.
dart';
bool useTimerToNavigate() {
return use(const _NavigateTimer());
}
class _NavigateTimer extends Hook {
const _NavigateTimer();
@override
___NavigateTimerState createState() =>
___NavigateTimerState();
}
class ___NavigateTimerState extends
HookState {
late Timer _timer;
bool isRedirect = false;
@override
void initHook() {
super.initHook();
_timer = Timer(Duration(seconds: 4), () {
Route route =
MaterialPageRoute(builder: (context) =>
HomePage());
Navigator.of(context).pushReplacement(
route);
});
}
@override
bool build(BuildContext context) {
return isRedirect;
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
}
And here is the final Splash Screen code!
// splash_screen.dart
class SplashScreen extends HookWidget {
@override
Widget build(BuildContext context) {
AnimationController
_animationController =
useControllerForAnimation();
Animation< Offset > offset =
useOffsetHook();
useTimerToNavigate();
return SafeArea(
child: Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFFFFFFFF),
Color(0xffE3F3FF)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Stack(
children: [
FadeTransition(
opacity: _animationController,
child: Center(
child: FlutterLogo(
size: 50,
),
// child:
Image.asset('assets/images/splashlogo.png'),
)),
Align(
alignment: Alignment.bottomCenter,
child: SlideTransition(
position: offset,
child: Image.asset(
'assets/images/splash_bg.png',
width: MediaQuery.of(context).size.width,
fit: BoxFit.fill,
),
))
],
),
),
));
}
}
The entire source is available on the
github: flutter-hooks-demo.
Conclusion
We can conclude that with the help of flutter
hooks we can reuse that AnimationController
and Animation< Offset > just by adding one
line!


AnimationController _animationController =
useControllerForAnimation();


So, this is how we can reduce the boilerplate
code and make a smaller size code for the
widget. And also make clean, easy and
maintainable code. I hope the Flutter hooks
tutorial was helpful to you. For more such
Flutter Tutorials, feel free to visit the Flutter
tutorials page and clone the github repository
to play around with the code.


If you are looking for Flutter experts who can
help you with your projects, contact us to hire
Flutter developer. Since our developers have
great problem-solving skills, we assure you of
the absolute code quality and optimum
application performance.
Thank You
www.bacancytechnology.com

More Related Content

PDF
Rich domain model
PPTX
PDF
객체지향적인 도메인 레이어 구축하기
PPTX
Building an Ethereum Wallet using Hashicorp Vault
PDF
우아한 객체지향
PDF
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
PDF
ေမာင္လွ ဇာတ္လမ္း ၂
PPTX
Dubai power point presentation
Rich domain model
객체지향적인 도메인 레이어 구축하기
Building an Ethereum Wallet using Hashicorp Vault
우아한 객체지향
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
ေမာင္လွ ဇာတ္လမ္း ၂
Dubai power point presentation

What's hot (20)

PPT
dubai presentation
PPTX
Dubai Landmarks
PDF
BigQuery의 모든 것(기획자, 마케터, 신입 데이터 분석가를 위한) 입문편
PDF
화성에서 온 개발자, 금성에서 온 기획자
PDF
엘라스틱서치, 로그스태시, 키바나
PPTX
Internet - Présentation
PDF
အႀကံႀကီးသူ
PPT
Powerpoint presentation of my country
PDF
အလွမျပည့္ခင္ေၾကြတဲ့ပန္း
PPTX
SPARQLによるLODの検索@第4回LODとオントロジー勉強会-
PPTX
Tourist attractions on the gold coast[1][1]
PPTX
Dubai Airports
PPTX
Micro Service Architecture의 이해
PDF
MLflowによる機械学習モデルのライフサイクルの管理
PDF
Atelier numérique : Créer son site web avec Wix
PDF
HTML5 Bangla Ebook.pdf
PDF
Gestion de formulaires en PHP
PDF
데이터 분석 프로젝트 관리 방법론
PDF
Ruby HTTP clients comparison
PPTX
차곡차곡 쉽게 알아가는 Elasticsearch와 Node.js
dubai presentation
Dubai Landmarks
BigQuery의 모든 것(기획자, 마케터, 신입 데이터 분석가를 위한) 입문편
화성에서 온 개발자, 금성에서 온 기획자
엘라스틱서치, 로그스태시, 키바나
Internet - Présentation
အႀကံႀကီးသူ
Powerpoint presentation of my country
အလွမျပည့္ခင္ေၾကြတဲ့ပန္း
SPARQLによるLODの検索@第4回LODとオントロジー勉強会-
Tourist attractions on the gold coast[1][1]
Dubai Airports
Micro Service Architecture의 이해
MLflowによる機械学習モデルのライフサイクルの管理
Atelier numérique : Créer son site web avec Wix
HTML5 Bangla Ebook.pdf
Gestion de formulaires en PHP
데이터 분석 프로젝트 관리 방법론
Ruby HTTP clients comparison
차곡차곡 쉽게 알아가는 Elasticsearch와 Node.js
Ad

Similar to Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and useanimationcontroller) (20)

PDF
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
PDF
How to implement react native animations using animated api
PPTX
How to Animate a Widget Across Screens in Flutter.pptx
PDF
Symfony on steroids
: Vue.js, Mercure, Panther
PDF
PDF
DOCX
Android animation in android-chapter17
PDF
The java swing_tutorial
PDF
The java rogramming swing _tutorial for beinners(java programming language)
PPTX
Keynote + Next Gen UIs.pptx
PDF
Baruco 2014 - Rubymotion Workshop
PDF
JetBot basic motion
PDF
How to build a react native app with the help of react native hooks
PDF
Angularjs - Unit testing introduction
PDF
Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...
DOCX
Using traits in PHP
PPTX
-Kotlin_Camp_Unit2.pptx
PPTX
-Kotlin Camp Unit2.pptx
PPT
Angular animate
PDF
GNURAdioDoc-8
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to implement react native animations using animated api
How to Animate a Widget Across Screens in Flutter.pptx
Symfony on steroids
: Vue.js, Mercure, Panther
Android animation in android-chapter17
The java swing_tutorial
The java rogramming swing _tutorial for beinners(java programming language)
Keynote + Next Gen UIs.pptx
Baruco 2014 - Rubymotion Workshop
JetBot basic motion
How to build a react native app with the help of react native hooks
Angularjs - Unit testing introduction
Progressively enhance your Symfony 4 app using Vue, API Platform, Mercure and...
Using traits in PHP
-Kotlin_Camp_Unit2.pptx
-Kotlin Camp Unit2.pptx
Angular animate
GNURAdioDoc-8
Ad

More from Katy Slemon (20)

PDF
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
PDF
Data Science Use Cases in Retail & Healthcare Industries.pdf
PDF
How Much Does It Cost To Hire Golang Developer.pdf
PDF
What’s New in Flutter 3.pdf
PDF
Why Use Ruby On Rails.pdf
PDF
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
PDF
How to Implement Middleware Pipeline in VueJS.pdf
PDF
How to Build Laravel Package Using Composer.pdf
PDF
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
PDF
How to Develop Slack Bot Using Golang.pdf
PDF
IoT Based Battery Management System in Electric Vehicles.pdf
PDF
Understanding Flexbox Layout in React Native.pdf
PDF
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
PDF
New Features in iOS 15 and Swift 5.5.pdf
PDF
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
PDF
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
PDF
Flutter Performance Tuning Best Practices From the Pros.pdf
PDF
Angular Universal How to Build Angular SEO Friendly App.pdf
PDF
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
PDF
Ruby On Rails Performance Tuning Guide.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
How Much Does It Cost To Hire Golang Developer.pdf
What’s New in Flutter 3.pdf
Why Use Ruby On Rails.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How to Implement Middleware Pipeline in VueJS.pdf
How to Build Laravel Package Using Composer.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
How to Develop Slack Bot Using Golang.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Understanding Flexbox Layout in React Native.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
New Features in iOS 15 and Swift 5.5.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Ruby On Rails Performance Tuning Guide.pdf

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Electronic commerce courselecture one. Pdf
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
Teaching material agriculture food technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Advanced IT Governance
PPTX
Big Data Technologies - Introduction.pptx
PDF
Modernizing your data center with Dell and AMD
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
cuic standard and advanced reporting.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Electronic commerce courselecture one. Pdf
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
20250228 LYD VKU AI Blended-Learning.pptx
Review of recent advances in non-invasive hemoglobin estimation
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Spectral efficient network and resource selection model in 5G networks
GamePlan Trading System Review: Professional Trader's Honest Take
Understanding_Digital_Forensics_Presentation.pptx
Advanced IT Governance
Big Data Technologies - Introduction.pptx
Modernizing your data center with Dell and AMD
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
MYSQL Presentation for SQL database connectivity
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
cuic standard and advanced reporting.pdf

Flutter hooks tutorial (part 1) flutter animation using hooks (use effect and useanimationcontroller)

  • 1. Flutter Hooks Tutorial (Part 1): Flutter Animation using Hooks (useEffect and useAnimation Controller) www.bacancytechnology.com
  • 2. Do you remember how we used to do programming before Flutter hooks weren’t part of Flutter? It was a bit difficult and overwhelming, right? Here’s a Flutter tutorial where we will explore pre-hooks and post-hooks Flutter life. We will learn how to use useEffect and useAnimationController in our demo app. Let’s get ready and build an application, then!
  • 4. Animation controller Manage animation Listen for updates Manipulate animation In this Flutter Hooks tutorial, we will learn how to install and build an animation demo using hooks in Flutter, and also, we will look at how we used to code before hooks weren’t introduced. Before moving on to the Flutter hooks tutorial, let’s discuss the basics of animation. We need to do the below things for animation, The default part is the “Animation,” There are two types of animation that Flutter supports.
  • 5. Tween Animation– It is the short form of in-betweening. The animation must define the start and endpoint. The animation will have a start value and then reaches the end value through various intermediate values. Physics-based Animation– It allows you to interact with an app more realistically and interactively. In simple words, an Animation controller is called whenever its value changes, Ticker calls tick function every frame. After each tick, it provides a callback function after it is started. In our case, the ticker listener is the controller.
  • 6. useEffect hook fetches data from a server and sets the fetch to the local state useState hook manages local states in apps useMemoized hook memoizes complicated functions to achieve optimal app performance useRef hook creates an object that has one mutable property. Flutter hooks have not received much visibility and acknowledgment, but that won’t make them less awesome. With the help of the flutter_hooks library, we can provide a robust way for managing the lifecycle of widgets by reducing code duplication and increasing code-sharing. Flutter provides in-built hooks as shown below:
  • 7. useCallback hook cache a function instance. useContext hook obtain the BuildContext of the building HookWidget useValueChanged Hook watches a value and calls a callback whenever the value changes. In this guide, we’ll use the useEffect hook for redirection after some duration, and useAnimationController hook to create an instance of AnimationController. Flutter, just like ReactJS, also gives you the opportunity of creating your custom hooks. We will discuss that later in the tutorial. Without further ado, let’s get started with the Flutter hooks tutorial.
  • 9. First of all, let’s see the splash screen animation demo without implementing flutter hooks and using the stateful widget; it needs to be mixed in with a TickerProviderStateMixin. And don’t forget to dispose of the animation controller. class SplashScreen extends StatefulWidget { const SplashScreen(); @override _SplashScreenState createState() => _SplashScreenState(); } class _SplashScreenState extends State with TickerProviderStateMixin { late AnimationController _animationController; late AnimationController controller; late Animation< Offset > offset
  • 10. @override void initState() { super.initState(); startTime(); _animationController = new AnimationController(vsync: this, duration: Duration(seconds: 3)); _animationController.repeat(reverse: false); controller = AnimationController(vsync: this, duration: Duration(seconds: 2)); offset = Tween< Offset >(begin: Offset(0.0, 1.0), end: Offset.zero).animate(controller); controller.forward(); }
  • 11. startTime() async { var duration = Duration(seconds: 3); return Timer(duration, navigatePage); } Future navigatePage() async { Route route = MaterialPageRoute(builder: (context) => HomePage()); Navigator.of(context).pushReplacement(ro ute); } @override void dispose() { _animationController.dispose(); controller.dispose(); super.dispose(); } ... }
  • 12. All of the above code is set up for animation. And then we will just apply these instances to our widgets/design. That is just easy to understand.
  • 14. How to Install Flutter hooks? Run the following command for installing flutter hooks flutter pub add flutter_hooks The command will update pubspec.yaml file of the dependencies section with flutter_hooks: VERSION_NUMER_HERE. OR you can directly update pubspec.yaml with flutter_hooks as shown below dependencies: flutter: sdk: flutter flutter_hooks:
  • 15. Save the file, and Flutter will install the dependency. Now, import the flutter_hooks library. import 'package:flutter_hooks/flutter_hooks.dart'; How to Implement Animation using Flutter Hooks? The first change to make is to replace the Stateful Widget with Hook Widget. And then, to initialize the animation controllers, we will use the useAnimationController() method, a default method provided by the flutter_hook library. And we can remove all boilerplate code from initState and dispose method.
  • 16. class SplashScreen extends HookWidget { @override Widget build(BuildContext context) { AnimationController _animationController = useAnimationController(duration: Duration(seconds: 4), initialValue: 1); _animationController.repeat(reverse: false); AnimationController controller = useAnimationController(duration: Duration(seconds: 3), initialValue: 1); controller.repeat(reverse: false, period: Duration(seconds: 4)); controller = useAnimationController(duration: Duration(seconds: 3), initialValue: 1); controller.repeat(reverse: false, period: Duration(seconds: 4));
  • 17. Animation< Offset > offset = Tween< Offset >(begin: Offset(0.0, 1.0), end: Offset.zero).animate(controller); controller.forward(); useEffect(() { Timer.periodic(Duration(seconds: 4), (time) { Route route = MaterialPageRoute(builder: (context) => HomePage()); Navigator.of(context).pushReplacement(ro ute); }); }); return SafeArea( child: Scaffold( body: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Color(0xFFFFFFFF),
  • 18. Color(0xffE3F3FF)], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: Stack( children: [ FadeTransition( opacity: _animationController, child: Center( child: FlutterLogo( size: 50, )), ), Align( alignment: Alignment.bottomCenter, child: SlideTransition( position: offset, child: Image.asset( 'assets/images/splash_bg.png', width: MediaQuery.of(context).size.width, fit: BoxFit.fill,
  • 19. ), )) ], ), ), )); } } But the problem with the above code is there is no way to dispose the animation controller instances; we have a solution for this, called custom hooks.
  • 21. The custom AnimationController hooks in Flutter will instantiate an AnimationController and return the ScrollController to use it from the UI. It will help in holding all the code, practically, which was previously stored in the State object of a StatefulWidget. The most basic hook can be just a simple function. Let’s create one under hooks/controller_for_animation.dart. And also one for Animation< Offset >. // hooks/controller_for_animation.dart. AnimationController useControllerForAnimation() { return use(_AnimControllerForAnimationHook()); } class _AnimControllerForAnimationHook extends Hook {
  • 22. @override _AnimControllerForAnimationHookState createState() => _AnimControllerForAnimationHookState(); } class _AnimControllerForAnimationHookState extends HookState { late AnimationController _animController; @override void initHook() { _animController = useAnimationController(duration: Duration(seconds: 4), initialValue: 1); _animController.repeat(reverse: false); } @override AnimationController build(BuildContext context) => _animController;
  • 23. @override void dispose() => _animController.dispose(); } Animation< Offset > useOffsetHook() { return use(_AnimOffsetForAnimationHook()); } class _AnimOffsetForAnimationHook extends Hook> { @override _AnimOffsetForAnimationHookState createState() => _AnimOffsetForAnimationHookState(); } class _AnimOffsetForAnimationHookState extends HookState, _AnimOffsetForAnimationHook> { late AnimationController _controller; late Animation< Offset > offset;
  • 24. @override void initHook() { _controller = useAnimationController(duration: Duration(seconds: 3), initialValue: 1); _controller.repeat(reverse: false, period: Duration(seconds: 4)); offset = Tween(begin: Offset(0.0, 1.0), end: Offset.zero).animate(_controller); _controller.forward(); } @override Animation< Offset > build(BuildContext context) => offset; @override void dispose() => _controller.dispose(); }
  • 25. All we did was move logic to this new class; also, there is one dispose method from which we can also dispose that controller, and now simply use that useControllerForAnimation. The method inside build method of the splash screen. class SplashScreen extends HookWidget { @override Widget build(BuildContext context) { AnimationController _animationController = useControllerForAnimation(); Animation< Offset > offset = useOffsetHook(); ……. }
  • 26. Also, create one hook widget inside hook/timer_widget.dart to redirect to a home screen after some duration. // hook/timer_widget.dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter_hooks_demo/home_page. dart'; bool useTimerToNavigate() { return use(const _NavigateTimer()); } class _NavigateTimer extends Hook { const _NavigateTimer();
  • 27. @override ___NavigateTimerState createState() => ___NavigateTimerState(); } class ___NavigateTimerState extends HookState { late Timer _timer; bool isRedirect = false; @override void initHook() { super.initHook(); _timer = Timer(Duration(seconds: 4), () { Route route = MaterialPageRoute(builder: (context) => HomePage()); Navigator.of(context).pushReplacement( route); }); }
  • 28. @override bool build(BuildContext context) { return isRedirect; } @override void dispose() { _timer.cancel(); super.dispose(); } } And here is the final Splash Screen code! // splash_screen.dart class SplashScreen extends HookWidget { @override Widget build(BuildContext context) { AnimationController _animationController = useControllerForAnimation();
  • 29. Animation< Offset > offset = useOffsetHook(); useTimerToNavigate(); return SafeArea( child: Scaffold( body: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Color(0xFFFFFFFF), Color(0xffE3F3FF)], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: Stack( children: [ FadeTransition( opacity: _animationController, child: Center( child: FlutterLogo( size: 50, ),
  • 30. // child: Image.asset('assets/images/splashlogo.png'), )), Align( alignment: Alignment.bottomCenter, child: SlideTransition( position: offset, child: Image.asset( 'assets/images/splash_bg.png', width: MediaQuery.of(context).size.width, fit: BoxFit.fill, ), )) ], ), ), )); } } The entire source is available on the github: flutter-hooks-demo.
  • 32. We can conclude that with the help of flutter hooks we can reuse that AnimationController and Animation< Offset > just by adding one line! AnimationController _animationController = useControllerForAnimation(); So, this is how we can reduce the boilerplate code and make a smaller size code for the widget. And also make clean, easy and maintainable code. I hope the Flutter hooks tutorial was helpful to you. For more such Flutter Tutorials, feel free to visit the Flutter tutorials page and clone the github repository to play around with the code. If you are looking for Flutter experts who can help you with your projects, contact us to hire Flutter developer. Since our developers have great problem-solving skills, we assure you of the absolute code quality and optimum application performance.