Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial, we will learn how to auto create model class from json file by making use of json model dart package library.
What is Json Model package?
Flutter json model package library is been used to create a model class from a json file. In other words this Library will help you to convert json data to model class for your flutter application.
Ok so let’s begin
Flutter : Auto Create Model from JSON file | json model Dart Package
Step 1 : Add Required Dependencies
Create a new Flutter project and add the following 4 dependencies.
To do so open pubspec.yaml file and add those.
dependencies
json_annotation : to create code for JSON serialization and deserialization.
dev_dependencies
json_model: used to generate model
build_runner: concrete way of generating files using dart code.
json_serializable: helps provider builder for handling JSON request.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
json_annotation: #to create code for JSON serialization and deserialization.
dev_dependencies:
flutter_test:
sdk: flutter
json_model: #used to generate json to model
build_runner: ^1.0.0 #concrete way of generating files using Dart code
json_serializable: ^2.0.0 #helps provides builder for handling JSON
JSON to Model class can be generated simple by using json_model but json model will also make use of json serializable for Mapping and all other Modeling Staff.
So just add the above 4 dependencies in your flutter project pubspec.yaml file.
Step 2 : Create folder and Create .json file
Then, after adding json model and other 3 dependencies, now you need to create a new folder by name “jsons” and inside that folder create a .json file and add some json data in it.
Create a “jsons” directory in root of your flutter project.
Create a json file under jsons directory.
Add below json data in that json file.
json data for model
{
"name": "Flash",
"power": "Speed Run : His connection to the Speed Force gives him plenty of abilities.",
"url": "https://m.media-amazon.com/images/M/MVXSDS_.jpg"
}
Check out my project structure in below image
Created a folder by name “jsons” and inside it created a .json file which has some json data in it
Step 3 : Go to Terminal and Run the Flutter Command
Once, you have created .json file and some json data in it, Now open your terminal and run the below Flutter Command
flutter packages pub run json_model
as shown below
What this command will do is, It will auto detect json file from jsons directory and create model from json data into your flutter project as shown below
Conclusion
Ok so in this tutorial we checked out how to auto-generate data model class from JSON file by using JSON MODEL dart package library.
Hi Guys, Welcome to Proto Coders Point, In this Programmer Blog post we will learn About What is Node.js and Why is Node js used for? and even we will check how to install NODE.JS on Ubuntu & Windows OS.
What is Node.js?
Node.js is basically an Open-Source Scripting Language, It is and JavaScript runtime Environment that executes JS codes outside a browser also.
The Node js will help the Back-End Developer use javascript to write server-side script to produce dynamic web page and fetch data from database before web page is sent to user’s browers.
In Short Node.js is and Open Source server environment which is completely free to used and Node.js is very speed and easily compatible on various OS platforms (Windows, Linus , Unix, Mac OS any many more)
Why NodeJS is Famous?
By using Simple JavaScript, we cannot get access to files system from browser but sometimes there is a situation, where we need to be able to read data from local file system sinse this is not possible by using Javascript.
In this sense we need something that we can use to interact directly with the computer file system, that’s what exactly what node.js allows us to do.
Node.js allows us to take javascript out of the browser by allowing us to interact directly with the computer data source.
Thus not we can access system files, Therefore by using Node.js we can also create a desktop application and Atom Editor is the best example that is built using Node.js.
Then, Now you can write javascript code not just for browser but also to make use of hardware component or file system.
Why node.js?
Well, node.js can be run on your own computer or somebody else computer rather say it you can run server script using Node.js on server computer.
Run the installer (the .msi file you downloaded in the previous step.)
Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).
node js installation
5. Restart your computer. You won’t be able to run Node.js® until you restart your computer.
6. Confirm that Node has been installed successfully on your computer by opening a Hyper terminal and typing in the commands node --version
You should see the version of node you just installed. So you can see my pc is been install with NodeJS version 12.17.0
Getting Started with NodeJS
Once Nodejs is been Installed successfully in your OS, Let’s use write a node script that will simply display ” HelloWorld” on the Browser.
Create a folder on your Desktop named “nodejs” under that folder Create a .js file named “helloworld.js”, and add the following code:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/h1'});
res.end("Hello World! Welcome to Proto Coders Point");
}).listen(8080);
console.log(" Server Running at : http://localhost:8080/");
Save the file.
Then Open Comment Prompt and run the below command
Hi Guys Welcome to Proto Coders Point, In this Android Tutorial we will learn how to implement password validation regex requirements in android app.
In other words Password Validation To check a password character must be minimum 8 character length which include alphebet, numeric digits and any special character symbol.
Password Validation requirements
Atleast 8 character in length.
Minimum One Uppercase.
Minimum One Number.
and should contain 1 Special Symbol.
Password Validation regex in android
Video Tutorial
Follow the below Steps and Code to integrate this validation textfield in android.
Step 1 : Create a new android project
offcourse you need to create a new Android Project or Open any existing project in android studio.
File > New > New Project > Empty Activity
Give a name to android project as “Password Validation android” or anything else as per your choice.
We are making use of android design library dependencies so that we can use material.textfield.TextInputLayout and androidx.cardview.widget.CardView in our android UI design.
Step 3 : Creating a Registration page UI
Open activity_main.xml file and copy page the below xml UI code.
Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar in flutter app development.
What is Snackbar?
A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar you can give a quick message, error or warning message to the app user,
One of the best and the most useful way of showing message or notification is by using Flutter Material Snackbar.
Of course, you need to create a new Flutter project in Android Studio or VSCode whichever is your favourite IDE.
Step2: Initialise a global key scaffold
Create a stateful class and declare a Global key scaffold state
final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
Step 3: Create a method of Snackbar bar
void _showSnackbar() {
final snack = SnackBar(
content: Text("This is Snackbar Example"),
duration: Duration(seconds: 15),
backgroundColor: Colors.green,
);
_globalKey.currentState.showSnackBar(snack);
}
Step 4: Call the method to show snackbar
Then, ok to call the method _showSnackbar we will make use of the RaisedButton widget in a flutter, when it is been pressed the method is been called and this method will showSnackBar using scaffordState globalkey.
RaisedButton(
onPressed: () {
_showSnackbar(); // calling the method on pressed
},
child: Text("Click me"),
),
1st. Way using _globalKey.currentState – Show Snackbar in flutter App
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',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Snackbar(),
);
}
}
class Snackbar extends StatefulWidget {
@override
_SnackbarState createState() => _SnackbarState();
}
class _SnackbarState extends State<Snackbar> {
final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _globalKey,
appBar: AppBar(title: Text("Flutter Snackbar Example"),),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("press to show Snackbar"),
RaisedButton(
onPressed: () {
_showSnackbar();
},
child: Text("Click me"),
)
],
),
),
);
}
void _showSnackbar() {
final snack = SnackBar(
content: Text("This is Snackbar Example"),
duration: Duration(seconds: 15),
backgroundColor: Colors.green,
);
_globalKey.currentState.showSnackBar(snack);
}
}
2nd. Way using ScaffoldMessenger.of(context).showSnackBar
Show Snackbar in flutter using ScaffoldMessenger.of(context).shotSnackbar(snackbar);
import 'package:flutter/cupertino.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(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SnackBarExample(),
);
}
}
class SnackBarExample extends StatefulWidget {
@override
_SnackBarExampleState createState() => _SnackBarExampleState();
}
class _SnackBarExampleState extends State<SnackBarExample> {
//creating an instance of Snackbar to use it in scaffoldMessenger
final snackBar = SnackBar(content: Text('New Way to show snackbar'),duration: Duration(seconds:1 ),action: SnackBarAction(
onPressed: (){
}, label: 'Button',
),);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
EButton(),
ElevatedButton(onPressed: (){
// using ScaffoldMessenger
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}, child: Text('New Snackbar')),
],
),
),
);
}
}
Conclusion
Yes, Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as customizable, so making use of the FlutterFlushbar library will remove this drawable and you can easily style as per your creativity that too without any scaffold.
This library is useful when you want to show more than a simple message.
Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar with flutter app development.
What is Snackbar in mobile app?
A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar you can give a quick message, error or warning message to the app user, One of the best and the most useful way of showing message is by using Flutter Material Snackbar.
But using Flutter default snackbars is not at all great now, This drawbacks of default snackbar we can solve with the use of Flutter Flushbar Library.
Flutter Flushbar plugin libray will work same like snackbars but the think is you can easily customize the snackbar as per you wish and it’s very much simple to use.
Flutter Flushbar library
After Creating a new Flutter project in your Favourite IDE platform like android studio or VSCode….
Adding dependencies
Then to add flushbar dependencies,
open pubspec.yaml file and all the following dependencies
dependencies:
flushbar: ^1.10.4
then, after adding hit the Pub get (to download the library).
This Simple Flushbar will displaybasically a copy of default Snackbar that by using Flushbar library,
To make it bit change i have added a simple click me button to it.
//Simple Flushbar with a button
void show_Simple_Flushbar(BuildContext context) {
Flushbar(
// There is also a messageText property for when you want to
// use a Text widget and not just a simple String
message: 'Hello from a Flushbar',
// Even the button can be styled to your heart's content
mainButton: FlatButton(
child: Text(
'Click Me',
style: TextStyle(color: Theme.of(context).accentColor),
),
onPressed: () { print("Simple snackbar example");},
),
duration: Duration(seconds: 3),
// Show it with a cascading operator
)..show(context);
}
The above snippet code is just a method by calling with a button press will show snackbar to the user. To call the Function you can just make use of MaterialButton widget.
As you can check that there’s no Scaffold or any boilerplate code, and it’s very easy to make snackbar styleable.
Output of simple Flushbar
Snackbar with Icons and more Information
Showing only Textual Info to user is not enough, Sometimes, we also need to show different kinds of information like warning, error message with some Icons on snackbar and Snackbar with different color, and thus it very easy to implement customized snackbar using Flushbar library.
Showing Snackbar using Flushbar library does not end here at just showing information or any message. You can really make use of this Flutter Flushbar library to customize snackbar as per you creativity,
This library can be customized in a sense like maing it rounded border, giving gradient background to snackbar and also custom animation or shadow effect.
void show_Custom_Flushbar(BuildContext context) {
Flushbar(
duration: Duration(seconds: 3),
margin: EdgeInsets.all(8),
padding: EdgeInsets.all(10),
borderRadius: 8,
backgroundGradient: LinearGradient(
colors: [Colors.green.shade800, Colors.greenAccent.shade700],
stops: [0.6, 1],
),
boxShadows: [
BoxShadow(
color: Colors.black45,
offset: Offset(3, 3),
blurRadius: 3,
),
],
// All of the previous Flushbars could be dismissed by swiping down
// now we want to swipe to the sides
dismissDirection: FlushbarDismissDirection.HORIZONTAL,
// The default curve is Curves.easeOut
forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
title: 'This is a floating Flushbar',
message: 'Lorem ipsum dolor sit amet',
)..show(context);
}
output
Customization doesn’t stop here, There are more properties of flushbar that you can use to modify snackbar. Please visit official site to learn more about Flushbar library.
Complete Flutter Flushbar code
Copy paste below lines of code in main.dart file
main.dart
import 'package:flutter/material.dart';
import 'package:flushbar/flushbar.dart';
import 'package:flushbar/flushbar_helper.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 FlushBar Example ',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Container(
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Flutter Snackbar Example - using Flushbar library",style: TextStyle(fontSize: 18,color: Colors.black,fontStyle: FontStyle.italic,decoration: TextDecoration.none),textAlign: TextAlign.center,),
),
MaterialButton(
child: Text("Simple",style: TextStyle(color: Colors.white),),
color: Colors.orange,
onPressed: (){
show_Simple_Flushbar(context);
},
),
MaterialButton(
child: Text("Text With Message n Icon",style: TextStyle(color: Colors.white),),
color: Colors.blue,
onPressed: (){
show_Title_n_message_Flushbar(context);
},
),
MaterialButton(
child: Text("Flush Bar Helper",style: TextStyle(color: Colors.white),),
color: Colors.green,
onPressed: (){
show_FlushbarHelper(context);
},
),
MaterialButton(
child: Text("Customized Flush bar",style: TextStyle(color: Colors.white),),
color: Colors.green,
onPressed: (){
show_Custom_Flushbar(context);
},
),
],
),
),
);
}
}
//Simple Flushbar with a button
void show_Simple_Flushbar(BuildContext context) {
Flushbar(
// There is also a messageText property for when you want to
// use a Text widget and not just a simple String
message: 'Hello from a Flushbar',
// Even the button can be styled to your heart's content
mainButton: FlatButton(
child: Text(
'Click Me',
style: TextStyle(color: Theme.of(context).accentColor),
),
onPressed: () {},
),
duration: Duration(seconds: 3),
// Show it with a cascading operator
)..show(context);
}
void show_Title_n_message_Flushbar(BuildContext context) {
Flushbar(
title: 'Success',
message: 'Form Submitted successfully',
icon: Icon(
Icons.done_outline,
size: 28,
color: Colors.green.shade300,
),
leftBarIndicatorColor: Colors.blue.shade300,
duration: Duration(seconds: 3),
)..show(context);
}
void show_FlushbarHelper(BuildContext context) {
FlushbarHelper.createInformation(
title: 'Exit',
message: 'Do you want to close the app ?',
).show(context);
}
void show_Custom_Flushbar(BuildContext context) {
Flushbar(
duration: Duration(seconds: 3),
margin: EdgeInsets.all(8),
padding: EdgeInsets.all(10),
borderRadius: 8,
backgroundGradient: LinearGradient(
colors: [Colors.green.shade800, Colors.greenAccent.shade700],
stops: [0.6, 1],
),
boxShadows: [
BoxShadow(
color: Colors.black45,
offset: Offset(3, 3),
blurRadius: 3,
),
],
// All of the previous Flushbars could be dismissed by swiping down
// now we want to swipe to the sides
dismissDirection: FlushbarDismissDirection.HORIZONTAL,
// The default curve is Curves.easeOut
forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
title: 'This is a customized Snackar',
message: 'Try it now ',
)..show(context);
}
Conclusion
Yes Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as per customizable, so making use of Flushbar library will remove this drawable and you can easily style as per you creativity that too without any scafford.
This library is useful when you want to show more that a simple message.
Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create a demo on how to check the state of internet connection using android broadcast receiver.
How to Check Internet Connection in android using Broadcast Receiver
Step 1: Create a new Project in android studio
OffCourse you need to Create a new Project,
Go to File > New Project and then fill all the details like app name, android package name, etc and hit the finish button to create new android project.
Step 2: add Network state permission on AndroidManifest.xml
Now, Open AndroidManifest.xml file and ACCESS_NETWORK_STATE permission
app > java > your package name ( right click ) > New > Java Class
Create a NetworkUtil class to find the network status as show below.
NetworkUtil.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
class NetworkUtil {
public static String getConnectivityStatusString(Context context) {
String status = null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
status = "Wifi enabled";
return status;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
status = "Mobile data enabled";
return status;
}
} else {
status = "No internet is available";
return status;
}
return status;
}
}
Step 5 : Create a broadcast receiver class
This broadcart receiver in android will keep track of when internet is connected or disconnected by using which we can easily update UI updates to the users.
app > java > your package name ( right click ) > New > Java Class
MyReceiver.java
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
Dialog dialog;
TextView nettext;
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
dialog = new Dialog(context,android.R.style.Theme_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.customdialog);
Button restartapp = (Button)dialog.findViewById(R.id.restartapp);
nettext =(TextView)dialog.findViewById(R.id.nettext);
restartapp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((Activity) context).finish();
Log.d("clickedbutton","yes");
Intent i = new Intent(context, MainActivity.class);
context.startActivity(i);
}
});
Log.d("network",status);
if(status.isEmpty()||status.equals("No internet is available")||status.equals("No Internet Connection")) {
status="No Internet Connection";
dialog.show();
}
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
Step 6 : update broadcast receiver in androidmanifest.xml
Then you need to update the broadcast receiver, so add the <receiver> tag in manifest file.
Under <application> tag just all the below <receiver> tag code.