Home Blog Page 7

How to convert an object into JSON in Flutter

0
Convert Object to JSON IN flutter DART

Hi Guys, Welcome to Proto Coders Point, In this Flutter dart article we will walk through How to convert an Object i.e. (Class Instance) into an JSON in Flutter dart.

1. Own Code to convert object to JSON without Library

The below example is manual way to convert object into JSON in flutter dart.

Below Steps:

  1. Create a class
  2. The class has a method to convert object into a Map.
  3. Finally convert the Map object to JSON String using JsonEncode() method.

Code

// main.dart
import 'dart:convert';

// Define a class
class User {
  final String userame;
  final int userage;
  final bool isMarried;

  User(this.userame, this.userage, this.isMarried);

  // Define a toJson method to convert User object to JSON
  Map<String, dynamic> toJson() {
    return {
      'name': userame,
      'age': userage,
      "isMarried": isMarried,
    };
  }
}

void main() {
  User user = User('Shubham', 25, true);

  // Convert User object to JSON
  String jsonString = jsonEncode(user.toJson());
  print(jsonString);
}
{"name":"Shubham","age":25,"isMarried":true}

The object code is manual method is flexiable, It is self written code that can convert object into json string and it don’t use any external library or dependencies.


2. Convert Object to JSON using json_serializable package

We will make use of json_serialiable using which we can generate code from JSON serialization & deserialization.

Steps:

1. Install required dependencies:

we need:

To install all the above 3 package run below command:

flutter pub add json_annotation json_serializable build_runner

then run

flutter pub get

2. Now, In Lib directory let’s create a file by name “user.dart” & then create class User & define it with @JsonSerializable() annotation example code below

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  String name;
  int age;

  // Use JsonKey to change the name of the field in JSON
  @JsonKey(name: 'is_admin')
  bool isAdmin;

  User(this.name, this.age, this.isAdmin);

  // The generated toJson method
  Map<String, dynamic> toJson() => _$UserToJson(this);

  // The generated fromJson method
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

3. user build_runner to generate JSON Serialization using below command

dart run build_runner build

By running above cmd a new file will get generated by name User.g.dart in the same directory where your class file exist.

generate JSON Serialization

You not need to enter the above code or edit anything in User.g.dart, as the code get automatically ganerated by build_runner.

4. Now simply use the ganeted code function i.e toJson() method that help you convert Object to JSON, if you want you can also use fromJson() to convert JSON data to an Object.

Below Code example

// lib/main.dart
import 'dart:convert' show jsonEncode;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'user.dart';

void main() {
  // Create a user object
  User user = User('Puppy Kute', 25, true);

  // Convert the user object to JSON
  Map<String, dynamic> jsonUser = user.toJson();

  // Print the JSON string
  if (kDebugMode) {
    print(jsonEncode(jsonUser));
    // Prints: {"name":"Puppy Kute","age":25,"is_admin":true}
  }

  // Create a list of user objects
  List<User> users = [
    User('Shubham', 40, false),
    User('Pavan', 50, true),
    User('Rajat', 28, false),
  ];

  // Convert the list of user objects to a JSON string
  List<Map<String, dynamic>> jsonUsers =
      users.map((user) => user.toJson()).toList();

  // Print the JSON string
  if (kDebugMode) {
    print(jsonEncode(jsonUsers));
  }
}
 [{"name":"Shubham","age":40,"is_admin":false},{"name":"Pavan","age":50,"is_admin":true},{"name":"Rajat","age":28,"is_admin":false}]

Conclusion

In this article we learn 2 ways by which we can convert Object to JSON. One is by self written code and another is by using external library’s like JSON_Serializable and build_runner.

Similar Articles

JSON in 2 Minutes

How to read json file in flutter & display a listview

Auto Create Model from JSON File in Flutter

Parse JSON data in flutter

AWS Lambda Function to Stop, Start or Restart AWS Instance

0
Start, Stop or Restart EC2 Instance using Lambda Function
Start, Stop or Restart EC2 Instance using Lambda Function

In this article, Let’s check out What is AWS Lambda Function & How we can use Lambda function to restart the EC2 server server instance.

Video Tutorial

What is AWS Lambda Function?

The AWS Lambda Function is a service provided by Amazon Web Services(AWS) that is basically a server less computing service. Using Lambda function we can run code without managing any servers instance. Here instead of building a overall server infrastructure, you can keep you focus on developing a application’s function code that can we executed when an events occurs or triggers is hit.

Basically AWS Lambda function is a server less computing system, Languages supported are Node.JS, Python, Java, Go, Ruby,C#, PowerShell and custom runtimes.

How to create a Lambda Function in AWS console?

1. SignIn into AWS Console.

2. In search box above search “Lambda”

how to create a lambda function in aws

select it.

3. Click on “Create Function” and fill the form

how to create a lambda function in aws

Here select "Autor from scratch", give a name to function, In Runtime select the language maybe python, nodejs or any other which you prefer to write code on. I select Python 3.11.

The AWS Lambda function get’s created, here is where you need to write your code.

how to create a lambda function in aws

How to change lambda execution time

Usually when you execute a lambda function by default the function execution timeout is 3 sec, suppose your lambda function need more time to execute the whole code then your code will stop execution after 3 sec and you may see an warning “Task timed out after 3.00 seconds”, so you need to change or config lambda function execution timeout below are steps to change timeout.

in lambda function, Goto Configuration -> general configuration, click on Edit

how to change lambda function execution time

Now change AWS lambda function timeout as per your need

AWS lambda function timeout

Note: This is required because sometime the code might require more then 3 sec to fully execute, In our case we are going to write a lambda function that stop our EC2 instance and start it again so for this process our server need at least 3-5 minute to start fully.


Giving permission to lambda function to access EC2 instance

As we are implementing a lambda function that can communicate to EC2 instance and perform event like stop, start or restart the instance server from lambda function itself we need to give permission to access EC2 instance. below are the step:

1. In AWS Console, Top Search Box, search for IAM, Enter the service.

2. Now on side menu goto Roles > select lambda function roles as shown in below image

Next in Permission tab > Permissions policies > click on Add Permission > Attach Policy

Now in Other permissions policies search box, search for “EC2FullAccess”

aws roles add permission for lambda function

Check the Check box and click on Add Permission

AmazonEC2FullAccess add permission to Lambda function

Once you add the roles permission to full access EC2 instance, your lambda function will be able to fully control your EC2 instance.


Lambda Python Code to Stop, Start EC2 Instance

Code – python

import boto3
import time
def lambda_handler(event, context):
    
    ec2 = boto3.client('ec2')
    
    # Specify the instance IDs of the instances you want to start
    instance_ids = ['i-091182e12341c19fd'] // replace with your ec2 instanceID

    
    # Stop the instances
    response = ec2.stop_instances(InstanceIds=instance_ids)
    
    time.sleep(300)

    # Start the instances
    response = ec2.start_instances(InstanceIds=instance_ids)
    print("Started")
    
    return response

To run the code, click on Deploy Button then click on Test Button

how to run lambda function

Structure of Atom – html + css animation

0
structure of atom animation using html and css only
structure of atom animation using html and css only

This article is on creating Structure of Atom with animation effect only using html and css.

via GIPHY

HTML Explaination – Structure of a Atom

We have a division tags that represent the structure of our Atom, This further contain sub-divisions –nucleous and orbits.

The Nucleous class holds protons and neutrons in a form of row.

The Orbits class container multiple electron elements, which simple represent electrons orbiting the nucleus.

The show-info div tag show a icon or button when clicked or hoverd we can show more information on the page using css.

The Info div will show different components on the atom, Including Innder and outer shells, detainls about the nucleus.

Code

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title> Structure of Atom </title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>

<h1>Carbon</h1>
<div class="atom">
	<div class="nucleous">
		<div class="row">
			<div class="proton"></div>
			<div class="proton"></div>
			<div class="neutron"></div>
			<div class="neutron"></div>
		</div>
		<div class="row">
			<div class="neutron"></div>
			<div class="neutron"></div>
			<div class="proton"></div>
			<div class="proton"></div>
		</div>
	</div>
	<div class="orbits">
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
		<div class="electron"></div>
	</div>
</div>
<div class="show-info">i</div>
<div class="info">
	<div class="inner-shell">			
		<div class="info-particle">
			<h3>INNER SHELL</h3>
			<p><strong>2</strong> ELECTRONS</p>
		</div>
	</div>
	<div class="outer-shell">
		<div class="info-particle">
			<h3>OUTER SHELL</h3>
			<p><strong>4</strong> ELECTRONS</p>
		</div>
	</div>
	<div class="inner-nucleous">
		<div class="info-particle">
			<h3>NUCLEOUS</h3>
			<p><strong>6</strong> PROTONS</p>
			<p><strong>6</strong> NEUTRONS</p>
		</div>
	</div>
</div>

  <script src='https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js'></script>
</body>
</html>

CSS Code – Structure of Atom

The body of html is ensured that the atom animation happens at the centered with proper aligment.

The atom structure class defines the properties of the atom, including it’s dimensions and appearance.

Nucleus and Electron

The Nucleus and Electron particulars are core compoments of the atom animation effect, The .nucleus class defines the appearance of the nucleus, while the .electron class sets the properties for the electrons. The animation properties dictate the duration, timing function, and iteration count for the electron animation.

Electron Orbits

The electron orbits are defined using the .orbit1, .orbit2, and .orbit3 classes, each with their respective animation-name properties pointing to the keyframe animations orbit1, orbit2, and orbit3.

The @keyframes rule specifies the animation code for each orbit, detailing the transformation for the electrons around the atom. The rotate and translateX functions play a crucial role in creating the circular motion effect.

code

body {
	margin: 0;
	padding: 0;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	background: repeating-conic-gradient(#FFF4 0%, transparent .0002%, transparent .075%, transparent .65%), repeating-conic-gradient(#FFF2 0%, transparent .0004%, transparent 0.05%, transparent .495%), radial-gradient(circle at 50% 50%, #121212, #000);
	perspective: 100vmin;
}

body * {
	transform-style: preserve-3d;
}

*::before {
	box-sizing: border-box;
}

h1 {
	position: absolute;
	top: 4vmin;
	color: #fff;
	font-family: Arial, serif;
	font-weight: normal;
	font-size: 3.5vmin;
	margin: 0;
}

.atom {
	width: 50vmin;
	height: 50vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
	transition: 0.4s ease 0s;
	cursor: zoom-in;
}

.atom:active {
	transform: scale3d(1.5,1.5,1.5);
}

.atom:before {
	content: "";
	width: 50vmin;
	height: 50vmin;
	position: absolute;
	background: radial-gradient(#913ab7 -50%, #fff0 50%);
	transform: translateZ(-6vmin);
	box-shadow: 
		0 0 5vmin -2vmin #cddc3920, 0 0 10vmin 0vmin #cddc3920, 
		0 0 10vmin 0vmin #39dcbe20, 0 0 10vmin 0 #cddc3920 inset, 
		0 0 25vmin 0 #39dcbe20 inset;
	border-radius: 100%;
	animation: orbit-cloud 3s ease 0s infinite alternate;
	opacity: 0.25;
}

@keyframes orbit-cloud {
	0% { filter: hue-rotate(0deg); }
	100% { filter: hue-rotate(50deg);}
}



/*** NUCLEOUS ***/

.nucleous {
	width: 16vmin;
	height: 16vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
}

.row {
	border-radius: 100%;
	transform: rotateX(80deg);
	position: absolute;
	width: 40%;
	height: 40%;
	margin-top: -8vmin;
	left: 33%;
	display: flex;
	align-items: center;
	justify-content: center;
	transform: rotateX(80deg) rotate(180deg);
	animation: orbit-nucleous 3s linear 0s infinite;
}

.row:nth-child(1) div:before {
	content: "";
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	margin-top: -11vmin;
	background: red;
	background: radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), radial-gradient(circle at 28% 57%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), radial-gradient(circle at 37% 71%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), radial-gradient(circle at 40% 60%, var(--c2), 1.65vmin, #fff0 calc(1.65vmin + 1px) 100%) var(--c1);
}

.row:nth-child(2) {
	--znt: 1.3,1.3,1.3;
	margin-top: 0vmin;
	animation: orbit-nucleous3 3s linear 0s infinite;
}


@keyframes orbit-nucleous {
	0% { transform: rotateX(80deg) rotate(0deg); }
	100% { transform: rotateX(80deg) rotate(360deg);}
}

@keyframes orbit-nucleous3 {
	0% { transform: rotateX(80deg) rotate(0deg) scale3d(var(--znt)); }
	100% { transform: rotateX(80deg) rotate(360deg) scale3d(var(--znt)); }
}

.row div {
	--c1: #bc0003;
	--c2: #fa0001;
	width: 6vmin;
	height: 6vmin;
	border: 1px solid #0006;
	border-radius: 100%;
	background: 
		radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), 
		radial-gradient(circle at 28% 57%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), 
		radial-gradient(circle at 37% 71%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), 
		radial-gradient(circle at 40% 60%, var(--c2), 1.65vmin, #fff0 calc(1.65vmin + 1px) 100%) 
		var(--c1);
	position: absolute;
	top: -3vmin;
	animation: orbit-nucleous-particle 3s linear 0s infinite;
}

@keyframes orbit-nucleous-particle {
	0% { transform: rotateX(90deg) rotateY(360deg) scale3d(0.75, 0.75, 0.75); }
	100% { transform: rotateX(90deg) rotateY(0deg) scale3d(0.75, 0.75, 0.75);}
}

.row div.neutron {
	--c1: #082976;
	--c2: #124b9c;
}

.row div:nth-child(2) {
	top: calc(100% - 3vmin);
}

.row div:nth-child(3) {
	left: -3vmin;
	top: calc(50% - 3vmin);
}

.row div:nth-child(4) {
	left: calc(100% - 3vmin);
	top: calc(50% - 3vmin);
}



/*** ELECTRONS ***/

.orbits {
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	animation: orbit-spin 180s linear 0s infinite;
}

@keyframes orbit-spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg);}
}

.orbits:before, .orbits:after {
	content: "";
	position: absolute;
	width: 100%;
	height: 100%;
	border-radius: 100%;
	animation: orbit-spin 180s linear 0s infinite;
	border: 0.2vmin dotted #CDDC3980;
	filter: blur(1px);
	opacity: 0.5;
}

.orbits:after {
	width: 60%;
	height: 60%;
	top: 20%;
	left: 20%;
	animation-direction: reverse;
	animation-duration: 90s;
}

.electron {
	--pos: rotateY(0deg);
	--tim: 2s;
	position: absolute;
	width: 100%;
	height: 100%;
	box-shadow: -10px 5px 3px -5px #CDDC3920 inset, 10px 0px 3px -5px #CDDC3920;
	border-radius: 100%;
	transition: all 0.4s ease 0s;
	transform: rotateX(80deg) rotate(180deg);
	animation: orbit-electron var(--tim) linear calc(var(--tim) * -0.5) infinite;
}

@keyframes orbit-electron {
	0% { transform: rotateX(80deg) var(--pos) rotate(0deg); }
	100% { transform: rotateX(80deg) var(--pos) rotate(-360deg);}
}

.electron:before {
	--c1: #8BC34A;
	--c2: #CDDC39;
	width: 1vmin;
	height: 1vmin;
	content: "";
	position: absolute;
	border-radius: 100%;
	box-shadow: 0 0 9px 0px #CDDC39;
	border: 1px solid #fff8;
	left: calc(50% - 0.5vmin);
	top: -0.5vmin;
	background: 
		radial-gradient(circle at 40% 60%, #fff0, 3vmin, #00000040 calc(3vmin + 1px) 100%), 
		radial-gradient(circle at 45% 73%, #fff, 0.3vmin, #fff0 calc(0.3vmin + 1px) 100%), 
		radial-gradient(circle at 27% 58%, #fff, 0.5vmin, #fff0 calc(0.5vmin + 1px) 100%), 
		radial-gradient(circle at 40% 60%, var(--c2), 1vmin, #fff0 calc(1vmin + 1px) 100%), var(--c1);
	transform: rotateX(90deg);
	animation: orbit-electron-particle var(--tim) linear 0s infinite;
}

@keyframes orbit-electron-particle {
	0% { transform: rotateX(90deg) rotateY(-360deg); }
	100% { transform: rotateX(90deg) rotateY(0deg);}
}

.electron:nth-child(2) {
	--pos: rotateY(70deg);
	--tim: 1.535s;
}

.electron:nth-child(3) {
	--pos: rotateY(40deg);
	--tim: 1.875s;
}

.electron:nth-child(4) {
	--pos: rotateY(110deg);
	--tim: 1.275s;
}

.electron:nth-child(n+5) {
	width: 67%;
	height: 67%;
	left: 18%;
	top: 18%;
}

.electron:nth-child(5) {
	--pos: rotateY(140deg);
	--tim: 1.125s;
}

.electron:nth-child(6) {
	--pos: rotateY(25deg);
	--tim: 1s;
}



/*** INFO ***/

.info {
	position: absolute;
	width: 98vw;
	height: 60vmin;
	z-index: -1;
	font-family: Arial, serif;
	display: flex;
	align-items: center;
	justify-content: center;
}

.inner-shell, .outer-shell, .inner-nucleous {
	width: 20.5vmin;
	height: 12vmin;
	position: absolute;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	opacity: 0.05;
	top: 40vmin;
	color: #fff;
	margin-right: 80vmin;
}

.inner-shell {
	margin-top: 0.95vmin;
}

.outer-shell {
	top: 10vmin;
	margin-right: 83.5vmin;
}

.info > div:before {
	content: "";
	position: absolute;
	width: 15vmin;
	height: 15vmin;
	border: 0.25vmin solid #fff0;
	border-left: 0.25vmin dotted #fff;
	border-radius: 100% 0 0 0;
	transform: rotate(-45deg);
	right: -25vmin;
	margin-top: -33vmin;
}

.info > div.outer-shell:before {
	transform: rotate(0deg);
	margin-top: 2vmin;
	right: -30vmin;
	height: 25vmin;
	width: 25vmin;
	clip-path: polygon(0 50%, 100% 100%, 100% 100%, 0% 98%);
}

.inner-nucleous {
	margin-left: 83vmin;
	margin-right: 0 !important;
	top: 19vmin !important;
	height: 17.5vmin !important;
}

.inner-nucleous:before {
	transform: rotate(155deg) !important;
	left: -34.125vmin;
	margin-top: 11vmin !important;
}

.inner-shell:after, .outer-shell:after, .inner-nucleous:after {
	content: "";
	position: absolute;
	width: 15vmin;
	height: 0;
	right: -14.5vmin;
	margin-top: -18vmin;
	z-index: 333;
	border-top: 0.25vmin dotted #fff;
	transform: rotate(-23deg);
}

.outer-shell:after {
	right: -6vmin;
	margin-top: 13.1vmin;
	transform: rotate(14deg);
	width: 6vmin;
}

.inner-nucleous:after {
	transform: rotate(0deg);
	left: -21.5vmin;
	margin-top: 2.75vmin;
	width: 21.5vmin;
}


.info-particle {
	position: absolute;
	width: 20vmin;
	height: 11.5vmin;
	left: 0;
	top: 0;
	border: 0.25vmin dotted #fff;
	border-radius: 0.2vmin;
}

.inner-nucleous .info-particle {
	height: 17.25vmin;
}

.inner-shell:hover,
.outer-shell:hover,
.inner-nucleous:hover{
	opacity: 1;
}



h3 {
	margin: 1vmin 0 1.25vmin;
	font-size: 1.9vmin;
	font-weight: normal;
	text-align: center;
	border-bottom: 0.25vmin dotted #fff;
	padding-bottom: 0.75vmin;
}

p {
	text-align: left;
	font-weight: normal;
	margin: 1vmin 0 3vmin -2.75vmin;
	font-size: 1.5vmin;
	padding-left: 5vmin;
}

p strong {
	font-size: 2.5vmin;
}

p:before {
	--c1: #8BC34A;
	--c2: #CDDC39;
	content: "\2212";
	position: absolute;
	width: 3vmin;
	height: 3vmin;
	border-radius: 100%;
	margin-left: -3.85vmin;
	background: radial-gradient(circle at 45% 45%, var(--c2), 1vmin, #fff0 calc(1vmin + 5px) 100%), var(--c1);
	box-shadow: 0 0 0.5vmin 0 #fff, 0 0 0.1vmin 0.15vmin #fff;
	color: #222;
	text-shadow: 1px 1px 2px #fff, -1px 1px 2px #fff, 1px -1px 2px #fff, -1px -1px 2px #fff;
	font-size: 3vmin;
	line-height: 3.15vmin;
	text-align: center;
}

p:after {
	content: "( NEGATIVE CHARGE )";
	position: absolute;
	bottom: -1.5vmin;
	left: 0;
	font-size: 1vmin;
	width: 100%;
	text-align: center;
}

.inner-nucleous p:before {
	--c1: #bc0003;
	--c2: #fa0001;
	content: "+";
}

.inner-nucleous p + p:before {
	--c1: #082976;
	--c2: #124b9c;
	content: "";
}

.inner-nucleous p:after {
	content: "( POSITIVE CHARGE )";
}
.inner-nucleous p + p:after {
	content: "( NO CHARGE )";
}


body:has(.outer-shell:hover) .atom .orbits .electron:nth-child(n+5),
body:has(.outer-shell:hover) .atom .nucleous {
	opacity: 0.15;
}

body:has(.inner-shell:hover) .atom .orbits .electron:nth-child(-n+4),
body:has(.inner-shell:hover) .atom .nucleous {
	opacity: 0.15;
}

body:has(.inner-nucleous:hover) .atom .orbits .electron {
	opacity: 0.15;
}

.show-info:hover + .info > div {
	opacity: 0.9;
}

.show-info {
	position: absolute;
	bottom: 4vmin;
	font-size: 3.5vmin;
	color: #fff;
	font-weight: bold;
	border: 0.25vmin solid #ffffffc9;
	width: 5vmin;
	height: 5vmin;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 100%;
}

.show-info:hover {
	color: #111;
	background: #fff;
	border-color: #111;
}


/*** PORTRAIT ***/

@media only screen and (orientation: portrait) {

	.info {
		height: 98vh;
	}

	.inner-nucleous {
		margin-left: 0vmin !important;
		margin-right: 0 !important;
		top: calc(50% + 32vmin) !important;
	}

	.inner-nucleous:before {
		transform: rotate(247deg) !important;
		left: -1.125vmin;
		margin-top: -75vmin !important;
	}

	.inner-nucleous:after {
		transform: rotate(90deg);
		left: -1.5vmin;
		margin-top: -41.25vmin;
		width: 23vmin;
	}

	h3 {
		font-size: 2.5vmin;
	}

	p {
		font-size: 2vmin;
	}

	p:after {
		font-size: 1.65vmin;
	}

	.info > div.outer-shell {
		margin-top: calc(50vh - 53.5vmin);
		margin-right: 47.5vmin;
	}

	.outer-shell:after {
		right: -4.5vmin;
		margin-top: 17.75vmin;
		transform: rotate(60deg);
	}

	.info > div.outer-shell:before {
		transform: rotate(52deg);
		margin-top: 33vmin;
		right: -28vmin;
	}

	.info > div.inner-shell {
		margin-right: -36vmin;
		margin-top: calc(50vh - 84vmin);
	}
	
	.inner-shell:after {
		width: 14vmin;
		right: 15.25vmin;
		margin-top: 25vmin;
		transform: rotate(105deg);
	}
	
	.inner-shell:before {
		transform: rotate(80deg) !important;
		right: 14vmin !important;
		margin-top: 51vmin !important;
	}

}

Conclusion

Implementing CSS to simple HTML page will enhance overall visual appearances of the web page. With the CSS snippet code provided above to build a super structure of atom animation, you can experiment and build upon this atom animation by making some changed into the code and add your own login, you can also exploring different properties & keyframe variations to create a more intricate and realistic representation of atomic structures.

Flutter Cupertino Timer Picker example with source code

0
FLUTTER CUPERTINO TIMER PICKER
FLUTTER CUPERTINO TIMER PICKER

Cupertino Timer Picker is IOS style timer picker in flutter, that allows user to search a duration of time or a time interval. In this Flutter Article let’s learn how to implement CupertinoTimerPicker in flutter with complete source code.

If you’re looking for a Cupertino-style timer picker i.e ios style time picker, then flutter provide a Timer Picker widget in Material Design class named CupertinoTimerPicker Here’s a basic example of how you can create a Cupertino-style timer picker:

We can make use of showCupertinoModalPopup widget to show a popup from the bottom of the screen.

Video Tutorial

Creating the Timer Picker Widget:

We have a function _showTimerPicker that open a popup at the bottom of the screen and displays the Timer Picker when a user press on a button to select a time duration user can select time in hours, minutes and seconds, To show type of mode that i.e. hms we can make use of mode property from CupertinoTimerPicker widget.

snippet – CupertinoTimerPacker Widget constructor

CupertinoTimerPicker(
{
 Key? key,
 CupertinoTimerPickerMode mode = CupertinoTimerPickerMode.hms,
 Duration initialTimerDuration = Duration.zero,
 int minuteInterval = 1,
 int secondInterval = 1,
 AlignmentGeometry alignment = Alignment.center,
 Color? backgroundColor, 
 double itemExtent = _kItemExtent, 
 required ValueChanged<Duration> onTimerDurationChanged
}
)

Handling Timer Selection and displaying selected time in Text Widget

The selected duration is stored in the selectedDuration variable initially it will be 0 for hours,minutes and seconds duration, When the user selects a new duration from Cupertino Timer Picker, the onTimerDurationChanged callback is triggered which has callback duration value selected using which we can update the selectedDuration using setState to reflect the user’s selection.

Source Code – CupertinoTimerPicker Flutter

Output

flutter cupertinotimerpicker
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  Duration selectedDuration = Duration(hours: 0,minutes: 0,seconds: 0);

  void _showTimerPicker(BuildContext context){
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context){
          return Container(
            height: 200,
            color: CupertinoColors.white,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [CupertinoButton(child: Text("DONE"), onPressed: (){
                    Navigator.of(context).pop();
                  })],
                ),
                Expanded(
                  child: CupertinoTimerPicker(
                     mode: CupertinoTimerPickerMode.hms,
                      initialTimerDuration: selectedDuration,
                      onTimerDurationChanged:  (Duration duration){
                       setState(() {
                         selectedDuration = duration;
                       });
                      }
                  ),
                )
              ],
            ),
          );
        }
        );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Selected Time ${selectedDuration.inHours} hours, ${selectedDuration.inMinutes % 60} mins, ${selectedDuration.inSeconds % 60} sec,'),
          SizedBox(height: 15,),
          ElevatedButton(onPressed: (){_showTimerPicker(context);}, child: Text("Show Time Picker"))
        ],
      ),),
    );
  }
}

Conclusion: This article introduced you to the Flutter Cupertino Timer Picker and showed you how to implement Time Picker in your flutter app in IOS style UI. You can further customize it to match the style of your app and use it to collect time-related input from your users.

References and Resources:

Related Article

Bottom Popup Cupertino action sheet flutter

easiest way to implement image picker in flutter

Date Time Picker in Flutter

File Picker in flutter

Google apis utilize in flutter

0
FLUTTER GOOGLE API
FLUTTER GOOGLE APIS

Hello guys, Welcome to Proto Coders Point. In this Flutter Article we discuss about Google apis Implement in flutter.

Examples of user-data APIs include Calendar, Gmail, and YouTube. 

Note: The only APIs you should use directly from your Flutter project are those that access user data via Google authentication. APIs that require service accounts should not be used directly from a Flutter application.

Direct use of service account-required APIs from a Flutter application is not advised. This necessitates the use of your application’s insecure shipping service credentials. We advise building an intermediary service in order to leverage these APIs.

Here describe use google api in flutter

Google APIs in flutter

Step 1 : Select the preferred API

The package’s API is listed on googleapis as a distinct Dart library using the name_version format. 

For an example let’s take youtube_v3 as an illustration.

In addition to being the class you must instantiate (see step 3), the Api class also exposes the scopes that stand for the permissions required to utilize the API. You can find the scopes available by looking under the Constants section of the YouTubeApi class. Use the youtubeReadonlyScope when authenticating the user to ask for permission to merely read an end-user’s YouTube data.

Import this library

import 'package:googleapis/youtube/v3.dart';

Step 2 : Turn on the API.

You need a Google project and an account on Google in order to access Google APIs. Additionally, you must turn on the desired API.

Using the console, enable an API for a project:

1) Visit the API Library for the Google Cloud console.

2) Choose the project you want to utilize from the list of projects.

3) Choose the API you want to activate from the API Library. Use the search bar and/or the filters if you need assistance finding the API.

4) Click ENABLE on the API page.


Step 3: Use the necessary scopes to authenticate the user

Users can authenticate with their Google identity by using the google_sign_in package. For each platform you want to support, you must configure sign-in.

Dependencies Within pubspec.yaml

dependencies:
  google_sign_in: 
  googleapis: 
import 'package:google_sign_in/google_sign_in.dart';

The desired permissions are supplied when the GoogleSignIn class is instantiated, as was covered in the previous section.

final _googleSignIn = GoogleSignIn(
  scopes: <String>[YouTubeApi.youtubeReadonlyScope],
);

To enable user authentication , adhere to the directions given by package:google_sign_in.

You must get an authenticated HTTP client after completing your authentication.


Step 4: Obtain an HTTP client that is authorized.

A GoogleSignIn extension method called authenticatedClient is offered by the extension_google_sign_in_as_googleapis_auth package.

import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';

OnCurrentUserChanged can be heard. You can design a client that is authorized if the event value is not null.

var httpClient = (await _googleSignIn.authenticatedClient())!;

When calling Google API classes, this Client instance already has the required credentials.


Step 5: Make the desired API class and use it.

Create the desired API type using the API, then call the methods, like in:

var youTubeApi = YouTubeApi(httpClient);

var favorites = await youTubeApi.playlistItems.list(
  ['snippet'],
  playlistId: 'LL',
);

The principles discussed on this page have a working implementation in the extension_google_sign_in_as_googleapis_auth example. We appreciate you joining us on a flutter journey! I hope you succeeded in finding what you sought.

Working with BLE devices in Flutter, Get List of BLE and Connect it.

0
Bluetooth Low Energy (BLE) In Flutter
Bluetooth Low Energy (BLE) In Flutter

In this flutter article, I’m excited to share an overview/baisc of what I have learnt whileworking with BLE in flutter application will provide you with flutter BLE code example with practical code simple, This flutter article on BLE might be a game changer.

Working with (Bluetooth Low Energy) BLE devices in flutter

Video Tutorial – BLE SCANNER

Flutter Blue Plus

A most popular package to work with Bluetooh Device in flutter is flutter_blue_plus package that provides Bluetooth Low Energy (BLE) functionality by using this package we can scan nearby bluetooth devices, connect with them & communicate with them.

Here is a step by step guide on how to work with BLE devices in flutter using flutter_blue_plus package.

Firstly we need to add BLE package into our flutter project follow below steps

1. Open pubspec.yaml file and under dependence section add

dependencies:
  flutter_blue_plus: ^1.16.2

2. Once package added you need to run below cmd to download the package as external dependencies

flutter pub get

3. To use flutter blue plue you need to import where required

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

Note:- Make sure you ask app users to accept bluetooth usage permission by prompt. Once users accepts the permission, you can start using mobile bluetooth into you flutter application.

Scan from BLE devices

Below is a snippet code to scan nearby BT devices

FlutterBluePlus flutterBlue = FlutterBluePlus.instance;

// Listens to BLE devices
flutterBlue.scanResults.listen((results){

// Hanlde discovered ble devices here

});

Connect to the devices

Once you find the available devices nearby you can connect to that particular devices using below method.

void connectToDevice(BluetoothDevice device) async{
    await device.connect();
}

Discover Services list

Don you know? each BLE devices has list of service that the device can provide, by connecting to in we can discover the list of services it has in it.

To fetch all the list of services that device has use below snippet code.

final services await device.discoverServices();

BLE Characteristics

Each services in BLE devices has list of it own characteristics, which is used to communicate with devices based on how it been manufactured. Fore Example:- Generic Access Services has list of BLS characteristics such as device name, MAC address etc.

Below is snippet code to list out characteristic of a services

for(var service in services){

  List<BlueToothCharacterictic> characteristics = service.characteristics;

}

Read Characteristics in BLE devices

Reading charactericistic retrive data from BT devices.

Create a Bluetooth Charactericistic Object then use read() method to perform read operation make sure to use await as read() is a asynchronous nature.

Snippet

BlueToothCharacterictic characteristics;

List<int> value = await characteristics.read();

//handle the value as needed

print(`Read Value: ${value.toString()}`);

Write Characteristics in BLE devices

Sending data to BLE devices to done by using write characteristics, We make use of write() methods make sure you use await with write() method.

You need to prepare the data to be sent as alist of integers, After the write operation you can listen for notification just to confirm that write was successful.

List<int> dataToSend = [0x01,0x02,0x03];

//write the data to characteristic
await characteristics.write(dataToSend);

Flutter BLE Scanner

Below is a source code, just an example how to implement BLE Scanner into Flutter Application

code

add dependencies in pubspec.yaml file

  flutter_blue:
  get: ^4.6.5
  permission_handler:

ble_controller.dart

The below Code have 2 main methods, One for scanning near by BLE ( Bluetooth Devices ) and another method is used for connecting to BLE devices.

import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class BleController extends GetxController{

  FlutterBlue ble = FlutterBlue.instance;
  
// This Function will help users to scan near by BLE devices and get the list of Bluetooth devices.
  Future scanDevices() async{
    if(await Permission.bluetoothScan.request().isGranted){
      if(await Permission.bluetoothConnect.request().isGranted){
        ble.startScan(timeout: Duration(seconds: 15));

        ble.stopScan();
      }
    }
  }

// This function will help user to connect to BLE devices.
 Future<void> connectToDevice(BluetoothDevice device)async {
    await device?.connect(timeout: Duration(seconds: 15));

    device?.state.listen((isConnected) {
      if(isConnected == BluetoothDeviceState.connecting){
        print("Device connecting to: ${device.name}");
      }else if(isConnected == BluetoothDeviceState.connected){
        print("Device connected: ${device.name}");
      }else{
        print("Device Disconnected");
      }
    });

 }

  Stream<List<ScanResult>> get scanResults => ble.scanResults;

}

main.dart

import 'package:ble_scanner_app/ble_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("BLE SCANNER"),),
        body: GetBuilder<BleController>(
          init: BleController(),
          builder: (BleController controller)
          {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  StreamBuilder<List<ScanResult>>(
                      stream: controller.scanResults,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Expanded(
                            child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: snapshot.data!.length,
                                itemBuilder: (context, index) {
                                  final data = snapshot.data![index];
                                  return Card(
                                    elevation: 2,
                                    child: ListTile(
                                      title: Text(data.device.name),
                                      subtitle: Text(data.device.id.id),
                                      trailing: Text(data.rssi.toString()),
                                      onTap: ()=> controller.connectToDevice(data.device),
                                    ),
                                  );
                                }),
                          );
                        }else{
                          return Center(child: Text("No Device Found"),);
                        }
                      }),
                  SizedBox(height: 10,),
                  ElevatedButton(onPressed: ()  async {
                    controller.scanDevices();
                    // await controller.disconnectDevice();
                  }, child: Text("SCAN")),

                ],
              ),
            );
          },
        )
    );
  }
}

building ble bluetooth scanner app in flutter

Conclusion

In this article, we learnt basic of BLE in flutter like how to discover list of BLE devices nearby, connecting to BLE Devices fetching services characteristic , reading & writing to device protocal in flutter application using flutter_blue_plus package.