Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Explore Shake Effect In Flutter

Animations are a fundamental piece of causing the UI of a mobile application to feel regular and smooth to the client. Smooth transitions and intelligent components make an application charming to utilize. Exacerbate the application through and through. Consequently, learning the basics of animations in any structure is a fundamental stage toward delivering a prevalent user experience.

This article will be Explore Shake Effect In Flutter. We will see how to implement a demo program. We are going to learn about how we can shake effect in your flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to implement a Shake Effect in a flutter. It shows how the Shake Effect will work in your flutter applications. It shows our widgets that shake when the user presses the button. Then, the widget will be shaken with some errors. It will be shown on your device.

Demo Module :


How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called animation_controller.dart inside the lib folder.

We will initially be going to make an animation controller class. We will require AnimationContoller to accomplish our desired impact, so we will make a different abstract state class.

import 'package:flutter/material.dart';

abstract class AnimationControllerState<T extends StatefulWidget>
extends State<T> with SingleTickerProviderStateMixin {
AnimationControllerState(this.animationDuration);

final Duration animationDuration;
late final animationController =
AnimationController(vsync: this, duration: animationDuration);

@override
void dispose() {
animationController.dispose();
super.dispose();
}
}

We will add the final Duration and the final animationController is equal to the AnimationController(vsync: this, duration: animationDuration). Also add dispose() method. In this method, we will add animationController.dispose().

Create a new dart file called custom_shake_widget.dart inside the lib folder.

We should characterize a StatefulWidget as a subclass that takes a child widget alongside a few adaptable properties. This widget will be mindful to shake our different widgets.

class CustomShakeWidget extends StatefulWidget {
const CustomShakeWidget({
required this.child,
required this.duration,
required this.shakeCount,
required this.shakeOffset,
Key? key,
}) : super(key: key);

final Widget child;
final double shakeOffset;
final int shakeCount;
final Duration duration;

@override
// ignore: no_logic_in_create_state
State<CustomShakeWidget> createState() => CustomShakeWidgetState(duration);
}

There are some properties are:

  • > child: This property is used for the widget that we want to shake.
  • > duration: This property is used for the Shake duration. It represents a difference from one point in time to another.
  • > shakeCount: This property is used for how many times our widget should shake
  • > shakeOffset: This property is used for the shake distance of the widget.

Note: CustomShakeWidgetState is public

Let’s define the CustomShakeWidgetState class with extends custom AnimationControllerState.

class CustomShakeWidgetState extends AnimationControllerState<CustomShakeWidget> {
CustomShakeWidgetState(Duration duration) : super(duration);
..................
.............
}

In this class, we will add a status audience to reset our AnimationController. This is significant as we need to show this error at various times and on the off chance that we don’t reset our controller then we can not see this impact once more.

@override
void initState() {
super.initState();
animationController.addStatusListener(_updateStatus);
}

@override
void dispose() {
animationController.removeStatusListener(_updateStatus);
super.dispose();
}

void _updateStatus(AnimationStatus status) {
if (status == AnimationStatus.completed) {
animationController.reset();
}
}

In the build method, we will utilize the animation with AnimatedBuilder and Transform. translate. We will return an AnimatedBuilder() technique. In this technique, we will add animationController and child. In a child, we will add the widget. child. Likewise, we will add a builder method.

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: animationController,
child: widget.child,
builder: (context, child) {
final sineValue =
sin(widget.shakeCount * 2 * pi * animationController.value);
return Transform.translate(
offset: Offset(sineValue * widget.shakeOffset, 0),
child: child,
);
},
);
}

In the class, we will likewise add the shake() strategy. This strategy will be liable for the shaken impact. This strategy ought to be public. We will add inside an animationController.forward().

void shake() {
animationController.forward();
}

Create a new dart file called main.dart inside the lib folder.

In the main. dart file, we will create a HomeScreen class. In this class, we will utilize GlobalKey to control the shaken impact (or to shake our widgets). Flutter gives GlobalKey that we can use as per our requirements regardless of the state. For this situation, we will require the state so we can start the shake during any taps. We will add two TextEditingControllers and three GlobalKeys.

late GlobalKey<FormState> _formKey;
late GlobalKey<CustomShakeWidgetState> _emailIDState;
late GlobalKey<CustomShakeWidgetState> _passwordState;
late TextEditingController _emailEditingController;
late TextEditingController _passwordEditingController;

We will create an initState() method. In this method, we will add _formKey is equal to the GlobalKey(), _emailIDState is equal to the GlobalKey(), _passwordState is equal to the GlobalKey(), _emailEditingController is equal to the TextEditingController(), and _passwordEditingController is equal to the TextEditingController().

@override
void initState() {
_formKey = GlobalKey();
_emailIDState = GlobalKey();
_passwordState = GlobalKey();
_emailEditingController = TextEditingController(text: "");
_passwordEditingController = TextEditingController(text: "");
super.initState();
}

Now, we will create a dispose() of the method. In this method, we will add all GlobalKey and TextEditingController.

@override
void dispose() {
_formKey.currentState?.dispose();
_emailIDState.currentState?.dispose();
_passwordState.currentState?.dispose();
_emailEditingController.dispose();
_passwordEditingController.dispose();
super.dispose();
}

In the body, we will create two TextformField widgets. In this widgets will wrap to CustomShakeWidget() method. In this method, we will add key, duration, shakeCount, and shakeOffset.

CustomShakeWidget(
key: _emailIDState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _emailEditingController,
decoration: const InputDecoration(
labelText: "Email id",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Email id is Invalid";
}
return null;
},
keyboardType: TextInputType.emailAddress,
),
),
),
CustomShakeWidget(
key: _passwordState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _passwordEditingController,
obscureText: true,
decoration: const InputDecoration(
labelText: "Password",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Password was Incorrect";
}
return null;
},
keyboardType: TextInputType.visiblePassword,
),
),
),

Now, we will create an ElevatedButton(). In this button, we will add style and the onPressed() function. Also, we will add a child. In a child, we will add the Text “Log In”. When the user presses the button then, our widget will shake with show some errors.

ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
onPressed: () {
_formKey.currentState?.validate();
if (_emailEditingController.text.isNotEmpty ||
_passwordEditingController.text.isNotEmpty) {
_emailIDState.currentState?.shake();
_passwordState.currentState?.shake();
}
},
child: const Text("Log In"),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_shake_effect_demo/custom_shake_widget.dart';
import 'package:flutter_shake_effect_demo/splash_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const Splash(),
);
}
}

class HomeScreen extends StatefulWidget {
const HomeScreen({
Key? key,
}) : super(key: key);

@override
State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
late GlobalKey<FormState> _formKey;
late GlobalKey<CustomShakeWidgetState> _emailIDState;
late GlobalKey<CustomShakeWidgetState> _passwordState;
late TextEditingController _emailEditingController;
late TextEditingController _passwordEditingController;

@override
void initState() {
_formKey = GlobalKey();
_emailIDState = GlobalKey();
_passwordState = GlobalKey();
_emailEditingController = TextEditingController(text: "");
_passwordEditingController = TextEditingController(text: "");
super.initState();
}

@override
void dispose() {
_formKey.currentState?.dispose();
_emailIDState.currentState?.dispose();
_passwordState.currentState?.dispose();
_emailEditingController.dispose();
_passwordEditingController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Shake Effect Demo"),
automaticallyImplyLeading: false,
backgroundColor: Colors.green,
centerTitle: true,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
CustomShakeWidget(
key: _emailIDState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _emailEditingController,
decoration: const InputDecoration(
labelText: "Email id",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Email id is Invalid";
}
return null;
},
keyboardType: TextInputType.emailAddress,
),
),
),
CustomShakeWidget(
key: _passwordState,
duration: const Duration(milliseconds: 800),
shakeCount: 4,
shakeOffset: 10,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: _passwordEditingController,
obscureText: true,
decoration: const InputDecoration(
labelText: "Password",
),
validator: (value) {
if (value?.isNotEmpty == true) {
return "Password was Incorrect";
}
return null;
},
keyboardType: TextInputType.visiblePassword,
),
),
),
const SizedBox(
height: 40,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
textStyle: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
onPressed: () {
_formKey.currentState?.validate();
if (_emailEditingController.text.isNotEmpty ||
_passwordEditingController.text.isNotEmpty) {
_emailIDState.currentState?.shake();
_passwordState.currentState?.shake();
}
},
child: const Text("Log In"),
),
],
),
),
),
),
);
}
}

Conclusion:

In the article, I have explained the Shake Effect basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Shake Effect On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Shake Effect in your flutter projectsWe will show you what the Introduction is. Make a demo program for working Shake Effect using the custom widget in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.