Saturday, July 14, 2018

Dart: Json Parsing

July 14, 2018

Welcome to this post.

In this post, I am going to cover about JSON parsing in Dart.

What I will do on this project?
 1.  Get data from Rest API.
 2.  Parse the JSON Data

Let's Start-

First, take look at the data source. I will get the data from this link.
https://swapi.co/api/starships/

JSON sample.
This response you will find that link
{
    "count": 37, 
    "next": "https://swapi.co/api/starships/?page=2", 
    "previous": null, 
    "results": [
        {
            "name": "Executor", 
            "model": "Executor-class star dreadnought", 
            "manufacturer": "Kuat Drive Yards, Fondor Shipyards", 
            "cost_in_credits": "1143350000", 
            "length": "19000", 
            "max_atmosphering_speed": "n/a", 
            "crew": "279144", 
            "passengers": "38000", 
            "cargo_capacity": "250000000", 
            "consumables": "6 years", 
            "hyperdrive_rating": "2.0", 
            "MGLT": "40", 
            "starship_class": "Star dreadnought", 
            "pilots": [], 
            "films": [
                "https://swapi.co/api/films/2/", 
                "https://swapi.co/api/films/3/"
            ], 
            "created": "2014-12-15T12:31:42.547000Z", 
            "edited": "2017-04-19T10:56:06.685592Z", 
            "url": "https://swapi.co/api/starships/15/"
        },
      ...
    ]
}

This is the json Sample. I just take only results data. It's a collection of the result. SO create the model class first.

Model Class

We have so many things on the JSON result.
so you have to create all the field.
Note: If you don't need some field, simply skip those.
  final String name;
  final String model;
  final String manufacturer;
  final String cost_in_credits;
  final String length;
  final String max_atmosphering_speed;
  final String crew;
  final String passengers;
  final String cargo_capacity;
  final String consumables;
  final String hyperdrive_rating;
  final String MGLT;
  final String starship_class;
  final List films;
  final List pilots;
  final String created;
  final String edited;
  final String url;
Note: here films and pilots are Lists, not String.

Now create the constructor-
RestModel(
      {this.name,
      this.model,
      this.manufacturer,
      this.cost_in_credits,
      this.length,
      this.max_atmosphering_speed,
      this.crew,
      this.passengers,
      this.cargo_capacity,
      this.consumables,
      this.hyperdrive_rating,
      this.MGLT,
      this.starship_class,
      this.films,
      this.pilots,
      this.created,
      this.edited,
      this.url});

Now create a factory method-
take a map and return a new RestModel.
factory RestModel.fromJson(Map<String, dynamic> json) {
      return new RestModel(
          name: json["name"] as String,
          model: json["model"] as String,
          manufacturer: json["manufacturer"] as String,
          cost_in_credits: json["cost_in_credits"] as String,
          max_atmosphering_speed: json["max_atmosphering_speed"] as String,
          crew: json["crew"] as String,
          passengers: json["passengers"] as String,
          cargo_capacity: json["cargo_capacity"] as String,
          consumables: json["consumables"] as String,
          hyperdrive_rating: json["hyperdrive_rating"] as String,
          MGLT: json["MGLT"] as String,
          starship_class: json["starship_class"] as String,
          films: json["films"] as List,
          pilots: json["pilots"] as List,
          created: json["created"] as String,
          edited: json["edited"] as String,
          url: json["url"] as String,
      );
  }

See the full class code of RestModel in Github.

Parse JSON

Now time for getting data from the internet-
Create the main function
void main() async{
}

Save the link in a String.
final link = "https://swapi.co/api/starships/";

Create a new list. And the subtype of this list will be RestModel
List<RestModel> list = new List();

import HTTP package and make a request
var res = await http.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});

next steps-
1. if the response code is 200 then the response is successful
2. decode the response code with the help of json class that include in the package 'dart:convert'
3. after decode it return a map.
4. take only 'result' from the map and save in a new variable.
5. loop this list and for every entry and return a new RestModel

See the code-

if (res.statusCode == 200) {
    var data = json.decode(res.body);
    var rest = data["results"] as List;
    for (var json in rest) {
	var model = new RestModel.fromJson(json);
	list.add(model);
	}
}

print the list
print("List Size: ${list.length}");

Output:
List Size: 10

Full code-

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'RestModel.dart';


void main() async{

	final link = "https://swapi.co/api/starships/";

	List<RestModel> list = new List();

	var res = await http
			.get(Uri.encodeFull(link), headers: {"Accept": "application/json"});

	if (res.statusCode == 200) {
		var data = json.decode(res.body);
		var rest = data["results"] as List;
		for (var json in rest) {
			var model = new RestModel.fromJson(json);
			list.add(model);
		}
		print("List Size: ${list.length}");
	}
}

That's it.
If you have any quires then use the comment section. Feel free to put comments.
you can easily parse json.
Happy Coding.

Read More

Wednesday, June 20, 2018

Dart: Variable

June 20, 2018

Welcome to the series post.
The is the first post about Dart

From today I am starting Dart language tutorial.
I already posted a brief introduction about dart and I also try to answer why you choose the dart programming. Check this Dart Introduction

In the previous post, I write about some important concept about dart. Before starting I recommend for taking a look.

Main method:
First, see the code:
void main(List<String> lists) {
}
In the code, you see that the parameter of the main method is a list of string. I think this is as usual of other programming languages. But most interesting part is that you can also create the main method without this parameter.
void main() {
}

So, That's so simple.
Now write a hello world program, to print something on the console, use print() function.
void main(List<String> lists) {
  print("Hello world");
}
Output:
Hello world

That's is the hello world program.
Now you can modify this program as yourself.

Variables:
Var:
To declare any variable you can use var keyword.
var v = 10;
you can put any type of data, like, Int, Double, String or anything
var string = "String";
var int = 10;
var double  = 30.0;
var boolean = false;

If you don't specify the value by default it considers as null
var value; //value is null

dynamic
You can use another keyword available name dynamic.
dynamic s = "s";
this dynamic type of variables can also hold any type of data, like var
dynamic string = "String";
dynamic int = 10;
dynamic double  = 30.0;
dynamic boolean = false;

You can also specify the data type of the data
String value;
int number;
double number2;
bool status;

Multiple variables:
You can also initialize multiple variables at the same time.
var a,b,c,d,e;
also, you can specify the value
var a1 = 10,b2 = 20,c2 = 30;

final and const:
If you need a variable that's value is not change after the declaration, use final keyword
final name = "Shudipto";
also the option for specific variables
final String type = "Student"; //explicitly

If you need runtime constant variables, then use const keyword
const value = 1000;
specific variable
const String data = "data:$value";

Lest see an example-
var foo = const [];
final bar = const [];
const baz = const [];
Here, [] create an empty list. and const[] creates an empty immutable list, it's denoted as (EIL)
In the above code,
foo => foo is currently an EIL.
bar => bar will always be an EIL.
baz => baz is a compile-time constant EIL.

It is possible to change the value of a non-final, non-const variable,
even if it used to have a const value.
foo = [];

It is not possible to change the value of a final or const variable.
// bar = []; // Unhandled exception.
// baz = []; // Unhandled exception.

that's it of the variable.

Comments:
single line comment: as usual like other languages. use '//'
//single line comment

multiline comment:
/*
* multi line comment
*/


That's the ending of today post.
Today in this article, I covered Hello world program and variable and Comments.

Thank you for reading.

Happy coding.

Read More

Sunday, June 3, 2018

Dart: Introduction

June 03, 2018

Welcome to this post.
Recently I start to learn Dart programming language.

From today, I will post about dart programming language.

dart
Src: Dartlang


What is dart?
Dart is an object-oriented programming language, developed by Google. It is used to build web, server, and mobile applications(Flutter).

Before Learning darts, some important concept, we have to understand.
Concepts:

  • Everything in darts is object and object is an instance of Class.
  • Even variable, function and null are object too.
  • Type annotation is optional because it is strongly typed. So we can special type or dynamic
  • Dart support generic type (for example a list of integers: List
  • Top level function is supported, we also used functions that tied to an object or a class. And another cool thing is it supports nested function
  • It also supports top-level variable and tied variables. The instance variable, sometimes known as fields or properties.
  • Like Java, Dart has no keyword like public, protected, private, If variables start with underscore (_) that consider as package private.
  • Dart tools can report only two kinds of problems. The first one is warnings that just indications of your code might not work, but they don’t prevent your program from executing. The second one is errors, it can be either compile-time or run-time and finally, it prevents the code from executing at all


That's the concept of dart. Now come where we can use this language.
Application of Dart
Dart is a scalable language. SO we write a simple script or full-featured app. we use this mainly 3 areas. Like-

Flutter - we can write a mobile app, that will run both Android and Ios.
Web - we can write an app that can run in modern web browser.
Dart VM - we can write command line app or server.


I think that's enough introduction about dart. So we can start learning.
In this blog, I will try to cover the basic of Dart.

So, Let's create a list of learning path of Dart programming Language.

What I will cover in this series tutorial -
  • Tutorial
    • Hello word
    • Variable
    • Data type
    • Function
    • Operators
    • String operation
    • Collection
    • Control flow statement
    • Classes
    • Methods
    • Enumerated types
    • Generics
    • Library and visibility
    • Asynchrony support
This is the learning path about dart. I will go through every topic.

That's the deal.
Stay connected with my blog. 

Read More