Home Blog Page 92

Hero Animation in Flutter Application Development

1
flutter hero animations
flutter hero animations

Hi Guys, Welcome to Proto Coders Point, In this Tutorial Will be implement  Hero Animation in flutter using a Widget Called Hero.

Hero Animation in Flutter Application Development

Hero Transition is a great to show an animation effect in flutter. They let’s the user know that they have changed the screens, while keeping the focus of the interaction.

Flutter has a widget  called Hero,That will automatically create an hero animation transition effect between two navigation Routes.

Hero Animation in Flutter Application Development

Flutter will figure out the widget in both routes & animate the chnages that happens between the route locations.

Let’s suppose you have to show animation effect on a image in flutter app as your UI Hero Animation.

Put it on both the page screen routes.

The one that you’ll be transition from (MyHomePage.dart) and the one you’ll be transition to (Screen2.dart).

Then just you need to Wrap the Flutter Image Widget with a Here Widget on both the Pages.

snippet Code of Hero Animation Widget

Hero(
              tag: 'image',
              child: Container(
                child: Image.asset('images/flash.png'),
                height: 300.0,
              ),
),

then you need to provide a tag to you hero Animation widget.

the Important thing is to use the same tag on both the pages,So that Flutter gets to know which Hero we are Animating.

Video Tutorial

Implementation of Flutter Hero Animation Widget to show Transition Effect

I have created new Flutter project in Android Studio, and then Created a 2 screens i.e main.dart and Screen2.dart

Copy and paste the below codes in respective dart files.

main.dart

hero animation in flutter
import 'package:flutter/material.dart';
import 'package:flutter_app_hero_animation/screen2.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      routes: {
        'screen2': (context) => Screen2(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Animation'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text("Go to Screen 2"),
            onPressed: () {
              Navigator.pushNamed(context, 'screen2');
            },
          ),
          Hero(
            tag: 'image',
            child: Container(
              child: Image.asset('images/flash.png'),
              height: 100.0,
            ),
          ),
        ],
      ),
    );
  }
}

Here in main.dart file i have created a Named routes from that i can easily Navigate from main.dart to Screen2.dart.

main.dart file have 2 main widgets that is a RaisedButton and an Hero widget that contains child as Container with in turn has a child with Widget Image.

Screen2.dart

hero animation in flutter
hero animation screen 2
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Screen2(),
    );
  }
}

class Screen2 extends StatefulWidget {
  @override
  _Screen2State createState() => _Screen2State();
}

class _Screen2State extends State<Screen2> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hero Animation'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'This is Screen 2',
              style: TextStyle(fontSize: 25.0),
            ),
            Hero(
              tag: 'image',
              child: Container(
                child: Image.asset('images/flash.png'),
                height: 300.0,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

as you can see in both the above pages codes that i have made user of Hero Widget that has a tag : ‘image’ with both the pages so that flutter can identify which widget should show Hero Animation

and All is set app is ready to show Hero Amination in your flutter app.

For Custom Animation in Flutter check out this post  here

Flutter Animation- Custom Animation Effect with Example

2
Flutter Animation Custom Animation Effect with Example
Flutter Animation Custom Animation Effect with Example

Hi Guys, Welcome to Proto Coders Point , In this Tutorial we will implement Flutter Animation with  example.

As usual you need to create new Flutter project or work with existing project

Introduction to Flutter from official site

So let’s begin implementation of Animation in Flutter

Flutter – Custom Animation Effect with Example

AnimationController Class

A Animationcontroller as the name itself says that it is used for an animation effects in Flutter Development.

This class lets you perform tasks such as:

Code Snippet

AnimationController controller;

controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
      upperBound: 100.0,
    );
    controller.forward();

    controller.addListener(() {
      setState(() {
        print(controller
            .value); //used to just print controller value to see changes
      });
    });

Duration : The length of time this animation should last.
If [reverseDuration] is specified, then [duration] is only used when going [forward]. Otherwise, it specifies the duration going in both directions.

vsync :  this

package:flutter/src/widgets/ticker_provider.dart mixin SingleTickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider
Provides a single [Ticker] that is configured to only tick while the current tree is enabled, as defined by [TickerMode].
To create the [AnimationController] in a [State] that only uses a single [AnimationController], mix in this class, then pass vsync: this to the animation controller constructor.
This mixin only supports vending a single ticker. If you might have multiple [AnimationController] objects over the lifetime of the [State], use a full [TickerProviderStateMixin] instead.

Center( 
       child: Container( 
       child: Image.asset('images/splash.png'), 
       height: controller.value, 
      ), 
),

In the above flutter animation i have simply gave an anim effect to an image where an image size gets increase within 3 seconds from Container height 0 to 100.

Here i am setting the container height from 0 – 100 in 3 seconds.

1. Flutter Animation Effect Example 1

Copy paste the Below lines of code in main.dart file of you animation project

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
      upperBound: 100.0,
    );
    controller.forward();

    controller.addListener(() {
      setState(() {
        print(controller
            .value); //used to just print controller value to see changes
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Custom Animation In Flutter"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Container(
                child: Image.asset('images/splash.png'),
                height: controller.value,
              ),
            ),
            Container(
              child: Text(
                "Animation Effect",
                style: TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.w500,
                    fontStyle: FontStyle.italic),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Output of above code flutter animation

custom Animation in flutter

The Above code will show the animation effect just once when the app is launched.

2.  Flutter Animation Effect for continues Animation.

so if you want to show any continous Animation that you can make user of Animation Class of flutter.

CurvedAnimation Class check official site here

CurvedAnimation Class

A CurvedAnimation defines the animation’s progress as a non-linear curve.

animation = CurvedAnimation(parent: controller, curve: Curves.easeIn);

Controlling the animation

animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse(from: 1.0);
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });

in the above snippet i am making use of 2 feature of AnimationController i.e reverse and forword.

that basically work something like this

controller.forword(); will work from small to high

controller.reverse(from:1.0); this will work from high to small.

Complete Code the get Continous animation effect

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation animation;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
      upperBound: 1.0,
    );
    controller.forward();

    animation = CurvedAnimation(parent: controller, curve: Curves.easeIn);

    controller.addListener(() {
      setState(() {
        print(animation
            .value); //used to just print controller value to see changes
      });
    });

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse(from: 1.0);
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Custom Animation In Flutter"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Container(
                child: Image.asset('images/splash.png'),
                height: animation.value * 100,
              ),
            ),
            Container(
              child: Text(
                "Animation Effect",
                style: TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.w500,
                    fontStyle: FontStyle.italic),
              ),
            )
          ],
        ),
      ),
    );
  }
}

But this animation will continue forever unless we trash the controller.

Even if this screen is dismissed that Controller will still be running and will make user of mobile memory or resources. So whenever you’re using animation controller in you project it’s really important that you tap it into dispose method.

@override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose(); // stop the animation
  }

This dispose method will stop the controller animation effect when the screen if been changed.

Output

Continous flutter animation effect
Continous animation effect

3. Change Background Color with Flutter Animation example 3

In this Flutter Animation example we are making user of ColorTween Class  to change the backgroudColor as an amination effect.

ColorTween Class has 2 properties begin and end where you need to specific the begin color and end color

begin ↔ Color

The value this variable has at the beginning of the animation.

end ↔ Color

The value this variable has at the end of the animation.

Complete Code to change the backGround Color with Flutter Animation

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation animation;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = AnimationController(
      duration: Duration(seconds: 5),
      vsync: this,
      upperBound: 1.0,
    );
    controller.forward();

    animation =
        ColorTween(begin: Colors.green, end: Colors.blue).animate(controller);

    controller.addListener(() {
      setState(() {
        print(animation
            .value); //used to just print controller value to see changes
      });
    });

//    animation.addStatusListener((status) {
//      if (status == AnimationStatus.completed) {
//        controller.reverse(from: 1.0);
//      } else if (status == AnimationStatus.dismissed) {
//        controller.forward();
//      }
//    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: animation.value, // animation effect to background
      appBar: AppBar(
        title: Text("Custom Animation In Flutter"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Container(
                child: Image.asset('images/splash.png'),
                height: 100.0,
              ),
            ),
            Container(
              child: Text(
                "Animation Effect",
                style: TextStyle(
                    fontSize: 30.0,
                    fontWeight: FontWeight.w500,
                    fontStyle: FontStyle.italic),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Then, The above code will give you Output like this

change background color using flutter animation

Then,As you can observe in above Gif image that the background color of the app is been changing.

Flutter Rich Text Widget – To show TextView with Some textStyle

1
Flutter Rich Text Widget
Flutter Rich Text Widget

Hi Guys welcome to Proto Coders Point, In the Tutorial, we will learn about the Flutter widget class i.e Rich Text.

Introduction to Flutter RichText widget

In Flutter, RichText is used to display multiply text styles.

Here, the text to be displayed is done using TextSpan objects.

The text which is displayed in the rich text widget should be styled explicitly. you can set a DefaultTextStyle using the current BuildContext to provide defaults. To learn more on how to style text in RichText Widget. see the documentation for TextStyle.

Implementation of Flutter Rich Text Example

ok, So we now know the basic of the above Flutter Text Widget. It’s time to implement the widget in our project. For that, we need to first create a new Flutter Project or you can continue with your existing one.

File > New > New Flutter Project

If you can’t find any option to create a flutter project that might be because you have not installed the flutter plugin into your android studio.

Check out this post to install flutter in android studio.

How to install flutter in android studio

Example of Flutter RichText with Code.

Code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Rich Text Demo"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: RichText(
          text: TextSpan(
            text: 'The harder you work for something,',
            style: TextStyle(fontSize: 15.0, color: Colors.lightBlue),
            children: <TextSpan>[
              TextSpan(
                text: ' The greater you\'ll feel when you achieve it',
                style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 20,
                    color: Colors.red),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Result:

Flutter rich text example

Here is another example of RichText Widget

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Rich Text Demo"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Column(
            children: <Widget>[
              Text(
                "Motivational Quotes",
                style: TextStyle(fontWeight: FontWeight.w800, fontSize: 25.0),
              ),
              RichText(
                text: TextSpan(
                  text: 'The harder you work for something,',
                  style: TextStyle(fontSize: 15.0, color: Colors.lightBlue),
                  children: <TextSpan>[
                    TextSpan(
                      text: ' The greater you\'ll feel when you achieve it',
                      style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 20,
                          color: Colors.red),
                    ),
                  ],
                ),
              ),
              Text(
                "Sentance 2",
                style: TextStyle(fontWeight: FontWeight.w900, fontSize: 30.0),
              ),
              RichText(
                text: TextSpan(
                  text: 'Your limitation',
                  style: TextStyle(fontSize: 15.0, color: Colors.lightBlue),
                  children: <TextSpan>[
                    TextSpan(
                      text: '— it\'s only your',
                      style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 20,
                          color: Colors.yellow[900]),
                    ),
                    TextSpan(
                      text: ' IMAGINATION.',
                      style: TextStyle(
                          fontWeight: FontWeight.w500,
                          color: Colors.green,
                          fontSize: 25),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }
}

Output – Result 

Flutter rich text flutter center
Flutter rich text flutter

Flutter RichText Widget is very much helpful when you want to show Text View in different TextStyle.

as in the above Code or image, I have made the Text font too big in the same sentence this you can’t Achieve using a normal Text Widget.

By you RichText in a flutter, we can Design the UI to show text to users as we want for example Making the first letter to be bigger in the sentence.

To learn more about flutter Widget visit the official Flutter site here

Flutter Data Table — A flutter widget of the week

0
Flutter DataTable
Flutter DataTable

Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Flutter Widget of the week i.e DataTable Flutter.

If you have some Important data to be shown to the user of flutter app,Then Flutter DataTable Will Help you to do that in tabular form.

Read More from official site.

Flutter Data Table — A flutter widget of the week

  • The DataColumn, which describes a column in the data table.
  • DataRow, which contains the data for a row in the data table.
  • DataCell, which contains the data for a single cell in the data table.
  • PaginatedDataTable, which shows part of the data in a data table and provides controls for paging through the remainder of the data.

Simple DataTable in flutter

Here is an snippit code to display simple DataTable in Flutter

DataTable(
           columns: [
             DataColumn(
                 label: Text(
               "USN",
               style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
             )),
             DataColumn(
                 label: Text(
               "Name",
               style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
             )),
             DataColumn(
                 label: Text(
               "Marks",
               style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
             )),
             DataColumn(
                 label: Text(
               "Percentage",
               style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
             )),
           ],
           rows: [
             DataRow(cells: [
               DataCell(Text("1")),
               DataCell(Text("Pavan")),
               DataCell(Text("99")),
               DataCell(Text("99%")),
             ]),
             DataRow(cells: [
               DataCell(Text("2")),
               DataCell(Text("Suraj")),
               DataCell(Text("85")),
               DataCell(Text("87%")),
             ]),
             DataRow(cells: [
               DataCell(Text("3")),
               DataCell(Text("Rajat")),
               DataCell(Text("89")),
               DataCell(Text("89%")),
             ]),
             DataRow(cells: [
               DataCell(Text("4")),
               DataCell(Text("Sanjay")),
               DataCell(Text("75")),
               DataCell(Text("80%")),
             ]),
           ],
         ),

In the above snippet code i have displayed Student data such as student USN, Name, Marks, Percentage.

Here is the Output of above code

flutter data table
flutter data table simple data

You can make any DataColumn as numerically bu just adding a line numeric: true which will show all the number data from right side of the DataColumn.

Eg:

DataColumn(
            label: Text(
            "Percentage",
            style:
            TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
           ),
numeric: true),

DataColumn numeric true
See the difference

As You see that Percentage Column has started displaying data from right side of DataColumn.

Show which Row is selected

You can show and default row as selected by setting selected attribute to true

DataRow(cells: [
                DataCell(Text("1")),
                DataCell(Text("Pavan")),
                DataCell(Text("99")),
                DataCell(Text("99%")),
              ], selected: true),

Here in above snippet code i have make DataRow 1 as Selected by default.

You can show a DataRow cell is editable or and gave a placeHolder

flutter dataTable properties

And the Important Every think in flutteer is an Widget so Feel Free to add any Widget in Flutter DataTable.

tooktip: used to show details of any column

When you long press on any DataTable you will a text pop up showing the use of that data or column.

tooltip:"Your message",

datatable flutter tooktip

Complete Code of Flutter DataTable Widget

This is the complete Code of Flutter Data Table Widget. You can Just Copy Paste the Code in main.dart file of you Flutter Project.

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
       
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter DataTable"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SingleChildScrollView(
            child: DataTable(
              sortAscending: true,
              sortColumnIndex: 0,
              columns: [
                DataColumn(
                    label: Text(
                      "USN",
                      style: TextStyle(
                          fontSize: 12.0, fontWeight: FontWeight.w900),
                    ),
                    tooltip: "Student USN Number"),
                DataColumn(
                    label: Text(
                  "Name",
                  style: TextStyle(fontSize: 12.0, fontWeight: FontWeight.w900),
                )),
                DataColumn(
                    label: Text(
                      "Marks",
                      style: TextStyle(
                          fontSize: 12.0, fontWeight: FontWeight.w900),
                    ),
                    numeric: true),
                DataColumn(
                    label: Text(
                      "Percentage",
                      style: TextStyle(
                          fontSize: 12.0, fontWeight: FontWeight.w900),
                    ),
                    numeric: true),
              ],
              rows: [
                DataRow(
                  cells: [
                    DataCell(Text("1"), showEditIcon: true),
                    DataCell(Text("Pavan")),
                    DataCell(Text("99")),
                    DataCell(Text("99%")),
                  ],
                  selected: true,
                ),
                DataRow(cells: [
                  DataCell(Text("2")),
                  DataCell(Text("Suraj"), showEditIcon: true),
                  DataCell(Text("85")),
                  DataCell(Text("87%")),
                ]),
                DataRow(cells: [
                  DataCell(Text("3")),
                  DataCell(Text("Rajat")),
                  DataCell(Text("Fill Marks"), placeholder: true),
                  DataCell(Text("89%")),
                ]),
                DataRow(cells: [
                  DataCell(Text("4")),
                  DataCell(Text("Sanjay")),
                  DataCell(Text("75")),
                  DataCell(Text("80%")),
                ]),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

 

 

How to parse json data in flutter dart programming

2
parse json in flutter
parse json in flutter

Hi Guys, Welcome to Proto Coders Point  In this Tutorial we will learn how to parse json data in dart ( flutter ) language.

Before that if  you are new in json and want to learn basic of json read this.

What is JSON Data ?

JSON stands for JAVASCRIPT OBJECT NOTATION , it’s an lightweight formated data for storing and transporting data very fast, JSON data are often used when data is to be sent from server to any application. Json is very easy for human being to read as it stored in text format.

refer in detail from below websites:

wikipedia : https://en.wikipedia.org/wiki/JSON

w3schools : https://www.w3schools.com/whatis/whatis_json.asp

JSON in dart ( Flutter )

Dart language has a built-in support for parsing json data.

You can easily convert json data into String using dart:convert library and map it with key: value parse, where keys are string and value are of dynamic objects.

import 'dart:convert';

You need to import dart:convert to convert json data.

Direct Json Parsing and How to use the data

var jsonData = '{ "name" : "ProtoCodersPoint", "website" : "protocoderspoint.com"  }'; //simple json data

var parsedJson = json.decode(jsonData); // need to import convert library

print('${parsedJson.runtimeType} : $parsedJson'); //Display full json Parse

print(parsedJson['name']); //fetch value using key 'name'

print(parsedJson['website']); // fetch value using key 'website'

Then, after Executing the above code you will get output like:

Ok So you can play with the json data using its key index, as you can see i m printing the data using it’s key in above lines of code.

Output

_InternalLinkedHashMap<String, dynamic> : {name: ProtoCodersPoint, website: protocoderspoint.com}
 ProtoCodersPoint
 protocoderspoint.com

JSON Parser using Object Class

Then, Instead of using json Parser directly, it’s better to pass the json data  to a class that handles your data from you. This can be done using a constructor in flutter dart.

class UserData {
  String name;
  String website;

  UserData(Map<String, dynamic> data) {
    name = data['name'];
    website = data['website'];
  }
}

Here I have defined an external class that will handle out json parser data, I have made use of Map which has datatypes as Map<String,dynamic>.

 var jsonData = '{ "name" : "Welcome", "website" : "protocoderspoint.com"  }'; //simple json data

 var parsedJson = json.decode(jsonData); // need to import convert library

 UserData userData = UserData(parsedJson); // creating an object and passed parsed JSON data

 print("${userData.name}  Keep learning from ${userData.website}");

Here i have parsed Json data using json.decode and then Created a class object names userData and passed parsed json data to class constructor.

Complete Code of parsing json data in flutter dart programming

Create a Flutter project in android-studio and copy paste the below lines of parse json in flutter code  main.dart file

main.dart

import 'package:flutter/material.dart';
import 'dart:convert';

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

String Welcome = "";
String website = " ";

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    var jsonData =
        '{ "name" : "Welcome", "website" : "protocoderspoint.com"  }'; //simple json data

    var parsedJson = json.decode(jsonData); // need to import convert library

    UserData userData = UserData(parsedJson);

    Welcome = userData.name;

    website = userData.website;

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("JSON PARSE DEMO"),
      ),
      body: Center(
        child: Text("${Welcome} keep Learning from ${website}"),
      ),
    );
  }
}

class UserData {
  String name;
  String website;

  UserData(Map<String, dynamic> data) {
    name = data['name'];
    website = data['website'];
  }
}

Output

parse json in flutter
Output of parse json in flutter

Recommended Articles

Android Tutorial on Volley library – How to Fetching JSON Data from URL

flutter generate model from json

Searching device UI a ripple animation android Background

0
Searching Device an Ripple Background
Searching Device an Ripple Background

Hello Guys, Welcome to Proto Coders Point, In this Android Article we will implement an android GitHub library called Ripple-background used to give device searching or ‘ripple animation android effect’

Which is the Ripple Effect Background?

An Android Ripple Background Github Library that provide an app with an beautiful ripple animation android.

To Learn in detail of this library visit official github site

This Beautiful Ripple background library is been created by Jason Yu Check out his other library they are an awesome android library and very easy to use and understand here

Demo of Ripple Searching device UI

Searching Device an Ripple Background animation gif
Searching Device an Ripple Background animation gif

Implementing Searching Device Ripple UI Background

Before we start implementing this library, I just want to say that in this tutorial we are simply Createing a ripple wave backgroud UI(User Interface), This tutorial will not actually search or find real time actual device near by.

So let’s begin adding some required staff into our project.

I assume that you have already created a new android project in your android-studio or you may also add this library in your existing project, all left to you it your choice.

Adding Dependencies in our project

Now, you to add library depencencies in your project. Open build.gradle(module: app)

dependencies {
        implementation 'com.skyfishjy.ripplebackground:library:1.0.1'
}

Then, Just copy paste the above  ripple background dependencies into dependencies section.

ripple background dependencies
ripple background dependencies

Then, all set, So the project can now easily use this library.

Adding UI of Ripple wave background in XML file

Here is a xml snippet code that will create a UI for the app, add the below lines of xml code into activity_main.xml file

<com.skyfishjy.library.RippleBackground
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content"
    app:rb_color="#0099CC"
    app:rb_radius="32dp"
    app:rb_rippleAmount="4"
    app:rb_duration="3000"
    app:rb_scale="6">
    <ImageView
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_centerInParent="true"
        android:id="@+id/centerImage"
        android:src="@drawable/demoImage"/>
</com.skyfishjy.library.RippleBackground>

Explaination of above code

app:rb_color: used to set the color of ripple background, i have set it to light blue.

app:rb_radius:  Radius is been used to set the cornor radius of the circle.

app:rb_rippleAmount: this will show ripple circle waves with some number.

app:rb_duration:  set the duration of the ripple circle animation.

app:rb_scale: set the scale of the one last animation cycle.

Ok so inside rippleBackground library their is a ImageView that i have used to start and stop the animation effect on click.

How to start the Animation Effect of ripple wave?

final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
 ImageView imageView=(ImageView)findViewById(R.id.centerImage);
 imageView.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         rippleBackground.startRippleAnimation();
     }
 });

same like of you want to stop the animation effect then use

rippleBackground.stopRippleAnimation();

 

Complete Code of Searching Device near by an Ripple Background – Android Github Library

Main_Activity.java

Copy paste the below lines of code in Main_Activity.java file

package protocoderspoint.com.ripplebackground;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.skyfishjy.library.RippleBackground;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

     boolean stop = false;
     Handler handler= new Handler();

     ImageView device;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
        device=(ImageView)findViewById(R.id.device);
        ImageView imageView=(ImageView)findViewById(R.id.centerImage);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!stop) // if stop is not true
                {
                    //then start the
                    rippleBackground.startRippleAnimation();
                    stop=true;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            foundDevice();
                        }
                    },3000);
                }
                else{
                    rippleBackground.stopRippleAnimation();
                    stop=false;
                    device.setVisibility(View.GONE);
                }

            }
        });
    }
    private void foundDevice(){
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(400);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        ArrayList<Animator> animatorList=new ArrayList<Animator>();
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(device, "ScaleX", 0f, 1.2f, 1f);
        animatorList.add(scaleXAnimator);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(device, "ScaleY", 0f, 1.2f, 1f);
        animatorList.add(scaleYAnimator);
        animatorSet.playTogether(animatorList);
        device.setVisibility(View.VISIBLE);
        animatorSet.start();
    }
}

In the above lines of code i have make use of IF ELSE statement to perform start and stop of the animation effect.

I have used a trigger which is of type Booleon to check if the animation of ripple is in start or stop state.

and if the animation of searching device started we will show an device found after 3 sec of start.

and set the found device to invisible as the user stops the amination.

activity_main.xml

Copy paste the above lines of code in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="15dp"
        android:textStyle="bold|italic"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:text="Searching New Device UI Animation"
        />

    <com.skyfishjy.library.RippleBackground

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content"
        app:rb_color="#0099CC"
        app:rb_radius="32dp"
        app:rb_rippleAmount="5"
        app:rb_duration="3000"
        app:rb_scale="6">
        <ImageView
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_centerInParent="true"
            android:id="@+id/centerImage"
            android:src="@drawable/searching"/>
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/device"
            android:layout_above="@id/centerImage"
            android:layout_marginBottom="32dp"
            android:layout_toLeftOf="@id/centerImage"
            android:layout_marginRight="6dp"
            android:src="@drawable/device"
            android:visibility="invisible"/>
    </com.skyfishjy.library.RippleBackground>

</LinearLayout>