Flutter Animation Widget Tutorial for Beginners

 

Flutter Animation :

Flutter animation tutorial where we can animate the widget in the fade in and fade out style in this part of the tutorial where we load the login form on button click.

Animations play an important role in app success, even a simple app will have some sort of animations like loading a dialog box.

Popular apps like swiggy, zomato, airtel cab services also use these animations to load maps and point vehicles to show user current location.

Also we can use the animation to load the image in splash screen and fade out once the time is up there are different types of animations available in flutter.

 

Flutter Animation Video Tutorial :

Go through the below tutorial for more detailed implementation.

 

Project Structure :

This image depicts the project structure of flutter animation

flutter animation

 

pubspec.yaml :

Add a animation plugin dependencies and update the version accordingly

dependencies:
  flutter:
    sdk: flutter
  animations: 1.1.2

 

widget.dart :

We are defining the widget so that we can use them in our project any where

Let us define the image view widget

Widget imageField() {
  return Image.asset('assets/login.png',width: 200,height: 200,);

}

 

Also we are defining the email and password widgets and for which we are also passing a validation as parameter to validate the fields

Widget emailField(validateEmail) {
  return TextFormField(
    keyboardType: TextInputType.emailAddress,
    decoration: InputDecoration(
      labelText: 'Email Address',
      hintText: 'abc@email.com',
    ),
    validator:
    validateEmail, //passing the reference of the validation mixin, not calling directly
    onSaved: (String value) {
      email = value;
    },
  );
}

 

Widget passwordField(validatePassword) {
  return TextFormField(
    obscureText: true,
    decoration: InputDecoration(
      labelText: 'Password',
      hintText: 'Password',
    ),
    validator: validatePassword,
    onSaved: (String value) {
      password = value;
    },
  );
}

 

And pass the submit button with parameter formkey

Widget submitButton(formKey) {
  return RaisedButton(
    color: Colors.red,
    child: Text('Login',style: TextStyle(color: Colors.white),),
    onPressed: () {
      if (formKey.currentState.validate()) {
        formKey.currentState.save();
      }
    },
  );
}

 

import 'package:flutter/material.dart';

String email = '';
String password = '';

Widget imageField() {
  return Image.asset('assets/login.png',width: 200,height: 200,);

}

Widget emailField(validateEmail) {
  return TextFormField(
    keyboardType: TextInputType.emailAddress,
    decoration: InputDecoration(
      labelText: 'Email Address',
      hintText: 'abc@email.com',
    ),
    validator:
    validateEmail, //passing the reference of the validation mixin, not calling directly
    onSaved: (String value) {
      email = value;
    },
  );
}

Widget passwordField(validatePassword) {
  return TextFormField(
    obscureText: true,
    decoration: InputDecoration(
      labelText: 'Password',
      hintText: 'Password',
    ),
    validator: validatePassword,
    onSaved: (String value) {
      password = value;
    },
  );
}

Widget submitButton(formKey) {
  return RaisedButton(
    color: Colors.red,
    child: Text('Login',style: TextStyle(color: Colors.white),),
    onPressed: () {
      if (formKey.currentState.validate()) {
        formKey.currentState.save();
      }
    },
  );
}

 

validation.dart :

Provide the validations for email and password so that we can pass the data to the class and parse accordingly here we are considering whether the field contains ‘@’ so that we can determine it as email..

String validateEmail(String value) {

  if (!value.contains('@')) {
    return 'Please enter a valid email';
  }

  return null;
}

 

and also defining the password validation with a minimum of 8 characters

String validatePassword(String value) {
  if (value.length < 8) {
    return 'Password must be more than 8 characters';
  }
  return null;
}

 

class Validation {
  String validateEmail(String value) {

    if (!value.contains('@')) {
      return 'Please enter a valid email';
    }

    return null;
  }

  String validatePassword(String value) {
    if (value.length < 8) {
      return 'Password must be more than 8 characters';
    }
    return null;
  }
}

 

main.dart :

We initialize the void main()

void main() => runApp(MyApp());

 

Return the MaterialApp

 MaterialApp(
  title: appTitle,
  home: MyHomePage(title: appTitle),
);

 

Declare the variables boolean and formKey

bool _visible = true;
final formKey = GlobalKey<FormState>();

 

Define the AnimatedOpacity widget and specify the opacity and also duration

AnimatedOpacity(

  opacity: _visible ? 1.0 : 0.0,
  duration: Duration(milliseconds: 500),
  
  child: 
),

 

We are animating the Container

Container(
  width: 300.0,
  height: 450.0,
  color: Colors.black12,
  
),

 

Define the widgets inside the Container

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    imageField(),
    emailField(validateEmail),
    passwordField(validatePassword),
    SizedBox(height: 20),
    submitButton(formKey),
  ],
),

 

Declare a floating button to make widget Visible and InVisible

floatingActionButton: FloatingActionButton(
  onPressed: () {
    // Call setState. This tells Flutter to rebuild the
    // UI with the changes.
    setState(() {
      _visible = !_visible;
    });
  },
  tooltip: 'Toggle Opacity',
  child: Icon(Icons.account_box),
),

 

FullCode :

Providing the full code for flutter animation integration

import 'package:flutter/material.dart';
import 'package:flutter_animation/widget.dart';
import 'package:flutter_animation/validation.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Widget Animation';
    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}


class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}


class _MyHomePageState extends State<MyHomePage> with Validation{
  // Whether the green box should be visible
  bool _visible = true;
  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: AnimatedOpacity(

          opacity: _visible ? 1.0 : 0.0,
          duration: Duration(milliseconds: 500),
          child: Container(
            width: 300.0,
            height: 450.0,
            color: Colors.black12,
            child:Center(
              child: Form(
                key: formKey,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      imageField(),
                      emailField(validateEmail),
                      passwordField(validatePassword),
                      SizedBox(height: 20),
                      submitButton(formKey),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Call setState. This tells Flutter to rebuild the
          // UI with the changes.
          setState(() {
            _visible = !_visible;
          });
        },
        tooltip: 'Toggle Opacity',
        child: Icon(Icons.account_box),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

 

Flutter AnimationĀ Output :

This screen depicts the usage of flutter animation

flutter animation

 

Show Buttons
Hide Buttons
Read previous post:
Flutter Gridview Orientation Tutorial for Beginners

  Flutter Gridview Orientation : Flutter gridview orientation make the view adjustable based on the screen orientation the number of...

Close