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

What's hot (20)

PPTX
Introduction to Docker
Pubudu Jayawardana
 
PDF
Linux Training For Beginners | Linux Administration Tutorial | Introduction T...
Edureka!
 
PPTX
Linux
salamassh
 
PDF
Android local sockets in native code
ramalinga prasad tadepalli
 
PPTX
Docker, Docker Compose and Docker Swarm
Carlos E. Salazar
 
PDF
Red Hat OpenShift Container Platform Overview
James Falkner
 
PDF
Hadoop installation, Configuration, and Mapreduce program
Praveen Kumar Donta
 
PDF
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
Akihiro Suda
 
PDF
Introduction to Docker
Luong Vo
 
PDF
The Pan-Canadian Trust Framework (PCTF) for SSI
SSIMeetup
 
PPTX
containerd the universal container runtime
Docker, Inc.
 
PPTX
Docker and containerization
Amulya Saxena
 
PDF
Workshop Docker for DSpace
Pascal-Nicolas Becker
 
DOCX
Xen工作原理
Chaozhong Yang
 
PPTX
Debian Linux Overview
DarshanRamjiyani
 
PDF
Docker storage drivers by Jérôme Petazzoni
Docker, Inc.
 
PDF
Introduction to Docker storage, volume and image
ejlp12
 
PDF
Streaming using Kafka Flink & Elasticsearch
Keira Zhou
 
PPTX
IP routing in linux
gamer007
 
Introduction to Docker
Pubudu Jayawardana
 
Linux Training For Beginners | Linux Administration Tutorial | Introduction T...
Edureka!
 
Linux
salamassh
 
Android local sockets in native code
ramalinga prasad tadepalli
 
Docker, Docker Compose and Docker Swarm
Carlos E. Salazar
 
Red Hat OpenShift Container Platform Overview
James Falkner
 
Hadoop installation, Configuration, and Mapreduce program
Praveen Kumar Donta
 
[KubeConUS2019 Docker, Inc. Booth] Distributed Builds on Kubernetes with Bui...
Akihiro Suda
 
Introduction to Docker
Luong Vo
 
The Pan-Canadian Trust Framework (PCTF) for SSI
SSIMeetup
 
containerd the universal container runtime
Docker, Inc.
 
Docker and containerization
Amulya Saxena
 
Workshop Docker for DSpace
Pascal-Nicolas Becker
 
Xen工作原理
Chaozhong Yang
 
Debian Linux Overview
DarshanRamjiyani
 
Docker storage drivers by Jérôme Petazzoni
Docker, Inc.
 
Introduction to Docker storage, volume and image
ejlp12
 
Streaming using Kafka Flink & Elasticsearch
Keira Zhou
 
IP routing in linux
gamer007
 

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
BOSC Tech Labs
 
PDF
Animations in Flutter - FlutterConf LATAM 2024
johnpryan
 
PPTX
Animation With Flutter.pptx
khushbu thakker
 
PDF
Animations in Flutter
Bartosz Kosarzycki
 
PDF
What are hooks in Flutter.pdf
AhmadBilal573315
 
PDF
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
DroidConTLV
 
PPTX
How to Animate a Widget Across Screens in Flutter.pptx
RubenGray1
 
PPTX
Keynote + Next Gen UIs.pptx
EqraKhattak
 
PDF
How to implement react native animations using animated api
Katy Slemon
 
PDF
A Complete Guide to Building Your First App with Flutter
beppamgadu
 
PDF
Bronx study jam 2
Peter Birdsall
 
PPTX
Animations avec Compose : rendez vos apps chat-oyantes
Antoine Robiez
 
PDF
Introduction to flutter
Wan Muzaffar Wan Hashim
 
PPTX
What is the Hero Class in Flutter Development.pptx
BOSC Tech Labs
 
PPTX
Flutter Road Map.pptx
abdullahwale
 
PDF
Tech winter break - GDG on campus PPT1.pptx.pdf
sanidhyanaik1907
 
PDF
Flutter in Action 1st Edition Eric Windmill
kiplesrhoder
 
PDF
Menambahkan Animasi ke Project Aplikasi Flutter - Widyarso Joko Purnomo
DicodingEvent
 
PDF
Flutter beyond hello world
Ahmed Abu Eldahab
 
PPTX
GoogleDSC_ GHRCE_ flutter_firebase.pptx
GoogleDeveloperStude22
 
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
BOSC Tech Labs
 
Animations in Flutter - FlutterConf LATAM 2024
johnpryan
 
Animation With Flutter.pptx
khushbu thakker
 
Animations in Flutter
Bartosz Kosarzycki
 
What are hooks in Flutter.pdf
AhmadBilal573315
 
Fun with flutter animations - Divyanshu Bhargava, GoHighLevel
DroidConTLV
 
How to Animate a Widget Across Screens in Flutter.pptx
RubenGray1
 
Keynote + Next Gen UIs.pptx
EqraKhattak
 
How to implement react native animations using animated api
Katy Slemon
 
A Complete Guide to Building Your First App with Flutter
beppamgadu
 
Bronx study jam 2
Peter Birdsall
 
Animations avec Compose : rendez vos apps chat-oyantes
Antoine Robiez
 
Introduction to flutter
Wan Muzaffar Wan Hashim
 
What is the Hero Class in Flutter Development.pptx
BOSC Tech Labs
 
Flutter Road Map.pptx
abdullahwale
 
Tech winter break - GDG on campus PPT1.pptx.pdf
sanidhyanaik1907
 
Flutter in Action 1st Edition Eric Windmill
kiplesrhoder
 
Menambahkan Animasi ke Project Aplikasi Flutter - Widyarso Joko Purnomo
DicodingEvent
 
Flutter beyond hello world
Ahmed Abu Eldahab
 
GoogleDSC_ GHRCE_ flutter_firebase.pptx
GoogleDeveloperStude22
 
Ad

More from Katy Slemon (20)

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

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
July Patch Tuesday
Ivanti
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
July Patch Tuesday
Ivanti
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 

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.