Home Blog Page 80

Flutter Snackbar Example | flushbar flutter Library

1
how to show snackbar in flutter

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).

get latest version on official site here.

Import the package

Then import flushbar package wherever you need to display snackbar to show some information.

import 'package:flushbar/flushbar.dart';
import 'package:flushbar/flushbar_helper.dart';

Now start using flushbar widget

1. Simple Flushbar

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

flutter snackbar example

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.

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);
}
snackbar with icons
A Flushbar with an icon and additional color

Fully Customized Flutter Snackbar

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

customized snackbar flutter

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.

 

How to check internet connection in android using Broadcast Receiver

0
How to check internet connection in android
How to check internet connection in android

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

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Step 3: Create a customDialog xml layout

This customDialog will be shown to user when user android device is not connect to internet.

how to check internet connectivity in android

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#024BFF"
    android:gravity="center"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:src="@drawable/no_internet"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Ooops!"
        android:gravity="center"
        android:textColor="#FFF"
        android:textSize="40sp"/>

    <TextView
        android:id="@+id/nettext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No Internet Connection found"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_marginBottom="10dp"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ON YOUR DATA AND HIT RESTART"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_marginBottom="10dp"
        android:gravity="center"/>

    <Button
        android:id="@+id/restartapp"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:text="Restart"
        android:textSize="20sp"
        android:background="@android:color/holo_green_light"/>

</LinearLayout>

Step 4: Create a new java class, NetworkUtil

Then, on the left Project section

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.

<receiver android:name = "MyReceiver">
            <intent-filter>
                <action android:name = "android.net.conn.CONNECTIVITY_CHANGE"
                    tools:ignore="BatteryLife" />
                <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
 </receiver>

Step 7 : Call Broadcast receive from MainActivity.java

Then you need to make a call to broadcast receiver so that broadcast receiver get activited from your android app.

This broadcast reciever will keep track of CONNECTIVITY_ACTION like internet connectivity on/off.

MainActivity.java

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity{

    private BroadcastReceiver MyReceiver = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyReceiver = new MyReceiver();
        broadcastIntent();
    }

    public void broadcastIntent() {
        registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(MyReceiver);
    }
}

Finally your android app is ready to check internet connection is on or off.

How to Generate SHA1 key fingerprint certificate for firebase android project

1
generate SHA-1 fingerprint certificate
Generate SHA-1 fingerprint certificate

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will learn about what is SHA1 key and SHA256 fingerprint and how to generate SHA-1 fingerprint certificate for your firebase android project.

What is the SHA1 key?

SHA1 key Stands for (Secure Hash Algorithm 1) is a cryptographic hash function that takes an input and generates a 160-bit (i.e 20-byte) hash value known as a message digest – This message digest is rendered as a hexadecimal number, which is if 40 digits long.

This Security technology was designed by United States National Security Agency, and is a U.S. Federal Information Processing Standard.

learn more about SHA-1 on wikipedia

https://en.wikipedia.org/wiki/SHA-1

How to Generate SHA1 certificate fingerprint?

Watch out this video tutorial to generate sha1 key certificate

OR

Continue here.

Open Command Prompt

You need to open Command prompt as Adminstration

Go to search in window and type cmd  and  then run as adminstration

run cmd prompt as admin

In command prompt enter this keytool cmd

Step 1

keytool -exportcert -v -alias androiddebugkey -keystore %USERPROFILE%/.android/debug.keystore

Enter keystore password : android

This will generate SHA fingerprint but will be in encrpted format ( unreadable ).

To make SHA fingerprint as readable enter cmd that is in Step 2.

Step 2

keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%/.android/debug.keystore

Enter keystore password : android

keytool sha-1 generate android debug keystore

Now you can see that SHA-1 and SHA256 are in readable format.

Then you can copy this SHA fingerprint and used then submit it in  firebase SHA-1 section.

Create API using Deno js & Display data in Flutter Listview builder

0
flutter deno js example

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will create our own API server using DENO JS scripting language and we will also create a flutter app that will fetch image data from our Deno API server script and display the Images in flutter deno application by making use of Flutter Builder and ListView Builder.

flutter deno api example

Brief Introduction on what is DENO ?

Deno is new Implementation of Node.js, We can call it as alternative of Node.js, The Creator of Deno and Node.js is the same “Ryan Dahl“, He it the original Creator of Node.js.

A Deno is a runtime JavaScript and TypeScript that is built on Version 8 of JavaScript engine and Deno is writter in Rust Programming language.

Creating API server using Deno Script | Deno js tutorial

Video Tutorial to create deno API

Step 1: Editor VSCode or Atom

I prefer to make use of vscode editor or Atom editor to write back-end scripts.

In my case i am using vscode editor.

Step 2: Create New project / New Folder

File > Open Folder (new folder) > “deno http server”

creating new folder in vscode

Then, Select Folder.

Step 3: Creating .ts files under deno http server folder

In vscode go to Files > New File  here create 2 files and name it as index.ts and ImageData.ts

Step 4: index.ts deno script code and ImageData.ts

Then, In index.ts file copy paste the below lines of deno code

index.ts

// we need denotrain module to create routes and application
import { Application, Router } from "https://deno.land/x/denotrain@v0.5.0/mod.ts";
import { imagedata } from "./imagesdata.ts";

const app = new Application({hostname:"192.168.0.7"}); // replace with you localhost IP Address

const routes = new Router();
// lets create router to the api server

app.use("/api",routes);

routes.get("/imagedata",(ctx)=>{
 return {
     // lets pass imagesdata interface here
     "imagedata":imagedata
 }
});

app.get("/",(ctx)=>{
 return "Hello World";
});  //this is the root of the server

await app.run(); // then finally run the app  press ctrl + ` to open terminal

ImageData.ts

interface Images{
    url:String;
}

export const imagedata : Array<Images> = [
    {
        "url":"https://images.wallpapersden.com/image/download/aladdin-2019-movie-banner-8k_65035_2560x1440.jpg",
    },
    {
        "url":"https://thumbor.forbes.com/thumbor/960x0/https%3A%2F%2Fblogs-images.forbes.com%2Fscottmendelson%2Ffiles%2F2017%2F07%2FJustice-League-SDCC-Banner.jpg",
    },
    {
        "url":"https://c4.wallpaperflare.com/wallpaper/869/847/751/movies-hollywood-movies-wallpaper-preview.jpg",
    },
    {
        "url":"https://www.pixel4k.com/wp-content/uploads/2018/09/x-men-days-of-future-past-banner_1536361949.jpg",
    },
    {
        "url":"https://images.wallpapersden.com/image/download/aquaman-2018-movie-banner-textless_63348_4000x1828.jpg",
    },
]

then, make sure you have saved both the files.

Step 5: Run the Deno Script to start the server

open terminal in your editor,

How to open terminal in editor?

press ctrl + ` to open terminal

Then run the deno js script using below command

deno run --allow-net index.ts

After running the command, your deno script API data we be serving at your hostname as show in below screenshot.

how to run deno script

My Deno script Imagedata router url is http://192.168.0.7:3000/api/imagedata

Deno will server me json format of Image Urls that i will be using in my Flutter application to load those image URL.

deno server api

Now we are done with Creating our own API using Deno Script.

Creating Flutter Application to Display Image in ListView Builder | Flutter Deno Example

Flutter Deno Example Video Tutorial

Step 1: Create a new Flutter Project

I am making Android Studio as my IDE to build Flutter Application

create a new Flutter Project in android studio and name the project as “Flutter Deno Example” or anything as per your choice.

Step 2: Add flutter http dependencies

As we are we are making network call we need to use flutter http library to fetch data from our deno api server.

open pubspec.yaml file and add the flutter http library under dependencies section.

http: ^0.12.1  #kindly check official site for latest version

Step 3: Method to Fetch Image Data from Server

//function to fetch image data from deno script server
fetchImageData() async{
  final url = "http://192.168.0.7:3000/api/imagedata";  // replace with your IP url
  var res = await http.get(url);
  return jsonDecode(res.body)["imagedata"];
}

The above method is making use of http call to get data from deno script and return data in json decoded format.

Step 4 : Display image Data using Future builder and Listview widget

This is just a snipcode, Complete flutter code is given at the end.

FutureBuilder(
        future: fetchImageData(),
        builder: (context,snapshot){
          if(snapshot.connectionState == ConnectionState.done)
            {
              if(snapshot.hasData)
                {
                  return ListView.builder(itemBuilder: (context,index){
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: Image.network(snapshot.data[index]["url"],fit: BoxFit.cover,),
                    );
                  },itemCount: snapshot.data.length,);
                }
            }else if (snapshot.connectionState == ConnectionState.none)
              {
                return Text("Something went Wrong");
              }
          return CircularProgressIndicator();
        },
      ),

In above Flutter code we are making use of:

FutureBuilder : Making use of FutureBuilder because loading/fetching data from server may take some time. Here  snapshot will hold all the data received from server.

Until data from server is completely loaded we will display CircularProgressIndicator() and once data is received we will show the data using ListView.builder that has Image widget to load url.

Complete Flutter Source Code | Flutter Deno Example

Copy paste below lines of Flutter Deno Example Source in main.dart file.

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;


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: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 20.0),
      height: 200.0,
      child: FutureBuilder(
        future: fetchImageData(),
        builder: (context,snapshot){
          if(snapshot.connectionState == ConnectionState.done)
            {
              if(snapshot.hasData)
                {
                  return ListView.builder(itemBuilder: (context,index){
                    return ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: Image.network(snapshot.data[index]["url"],fit: BoxFit.cover,),
                    );
                  },itemCount: snapshot.data.length,);
                }
            }else if (snapshot.connectionState ==ConnectionState.none)
              {
                return Text("Something went Wrong");
              }
          return CircularProgressIndicator();
        },
      ),
    );
  }
}

//function to fetch image data from deno script server
fetchImageData() async{
  final url = "http://192.168.0.7:3000/api/imagedata";
  var res = await http.get(url);
  return jsonDecode(res.body)["imagedata"];
}


Done now your Flutter applications is ready to fetch data from your own deno API script.

Recommended Article

how to install deno js – Deno Hello World Example

How to install Deno in Windows | Basic of Deno Script HTTP server

0
install deno js deno script http server hello world
install deno js deno script http server hello world

Hi Guys, Welcome to Proto Coders Point, In this tutorial, we will install Deno JS in Windows OS & learn some basics of denojs scripting language.

What is Deno? Who is the creator of Deno?

Deno is the new Implementation of Node.js, We can call it an alternative of Node.js, The Creator of Deno and Node.js is the same Ryan Dahl“, He is the original Creator of Node.js. A Deno is a runtime JavaScript and TypeScript that is built on Version 8 of the JavaScript engine and Deno is written in Rust Programming language. Deno explicitly takes on the role of both runtime and package manager within a single executable, rather than requiring a separate package-management program. Ryan Dahl during his talk says “10 Things I Regret About Node.js” ( You can Watch His talk in below video )

and is intended to fix design problems in Node.js, Ok so straight Start Installing Deno on Windows OS.

How to Install Deno on Windows?

Note: This steps are only for windows user.

Video Tutorial Watch :

Step 1: Scoop/Chocolatey must be Installed

You required any of this Scoop or Chocolatey that will help you in Installing Deno on windows,

a) How to install Scoop on windows

Run Command Prompt as Admin:  just copy paste below lines of commands & hit enter.

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\scoop\bin"
scoop install

This will install Scoop on your windows OS.

b) How to install Chocolaty on windows

Run Command Prompt as Admin:  just copy paste below lines of commands & hit enter.

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

This will install Chocolaty on your OS.

Step 2: Install Deno using Scoop or Chocolately.

After you have installed scoop or chocolately, now you can use then to install deno 

Then in Command Prompt just enter any of the below command.

scoop install deno
installing deno using scoop

OR

choco install deno

Step 4 : Test Deno

Then,Once you install deno, you to check if deno is installed successfully just in command prompt type : deno, This will run deno.

deno execution

In above Screenshoot, i have used deno to perform basic arithmetic operations.

Deno script to perform basic HTTP server

Use any Code Editor, In my Case, I am making use of VSCode to write my Deno Script. This Script is will basically print “Hello World” text on the Browser screen.

In VSCode editor Create a new Folder and name it as “Deno_http_server”.

vs code creating new folder for deno http server

Under this folder you need to create a new index.ts file

creating file in vscode for deno scripting

Copy the Below Deno Script HTTP server ” deno Hello World” in index.ts

import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello World\n" });
}

Ok then, to run this index.tx file.

Open Terminal in VsCode itself by pressing ctrl + Then run below command,

deno run --allow-net index.ts

screenshot example:

how to run deno script

Output

deno hello world output
deno hello world output

Related Article

Creating API using DENOJS & display listview in flutter app

Flutter Video Player Widget Tutorial

0
flutter video player widget plugin

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will build a Flutter application by making use of Flutter Video Player Widget Plugin to display/play videos in our Flutter App with example.

Introduction to video player flutter widget

Flutter Video Player is a plugin developed by the flutter team for Android, iOS, and Web development so that developers can easily make use of this video pkg widget library in integrating playing videos in their apps.

Important Note: As mentioned in official site that, This plugin is still under development, some latest API version of this video player library may give some kind of bugs.

let’s Start with installation of this widget in our flutter project

Flutter Video Player Widget Tutorial

Video Tutorial

Step 1: Create a new Project

offCourse you need to create a new Flutter Project or Open any existing project, all depends to you.

In my case, I m making use of Android Studio to Develop Flutter application.

Files > New > New Flutter Project

Step 2: Installation of Video Player Plugin

Adding dependencies

Open pubspec.yaml file and add the below video_player flutter dependencies version

dependencies:
  video_player: ^2.1.1 // version might change so check the official site

Import the video_player.dart

Once you have added the video player plugin, now you will be able to use video pkg by importing the library file where required.

import 'package:video_player/video_player.dart';

In my case i have imported video_player.dart file in main.dart file

Step 3: Adding Internet permission in android and iOS

Android

Please make sure to add the following Internet permission in your Android project manifest file.

Naviget to : <project root>/android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>

The Flutter project template adds it, so it may already be there.

iOS

For iOS devices Navigate to <project root>/ios/Runner/Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

and just add the above keys.

Step 4 : Network configuration android version 9 ( Optional )

This Step is optional, do this only if you are facing any problem in loading the video.

Create a directory names ” xml ” under the following path:

<project root>/android/app/src/main/res

In this xml folder you need to create a new xml resource file  

xml(dir) > (Right click) New > xml Resource file > and name the file as networkconfig.xml

Then, add the following Network Config code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">commondatastorage.googleapis.com</domain>  //here replace with you localhost server or your domain name
    </domain-config>
</network-security-config>

Here is example of the directory structure:

network config android

Step 5 : The Complete Code for Flutter Video Player

main.dart 

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

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

  VideoPlayerController controller; // used to controller videos
  Future<void> futureController;  // network takes time to load video, so to control future video data

  @override
  void initState() {

    //url to load network
    controller = VideoPlayerController.network("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");
    futureController = controller.initialize();

    controller.setLooping(true);  // this will keep video looping active, means video will keep on playing
    controller.setVolume(25.0);  // default  volume to initially play the video 
    super.initState();

  }

  @override
  void dispose() {
    controller.dispose();  // when app is been closed destroyed the controller
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(
        title: Text("Flutter Video Player Example"),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: FutureBuilder(
              future: futureController,
              builder: (context,snapshot){
                // if video to ready to play, else show a progress bar to the user
                if(snapshot.connectionState == ConnectionState.done)
                  {
                    return AspectRatio(
                      aspectRatio: controller.value.aspectRatio,
                      child: VideoPlayer(controller)
                    );
                  }else{
                    return Center(child: CircularProgressIndicator(),);
                }
                
              },
            ),
          ),
          //button to play/pause the video
          RaisedButton(
            color: Colors.transparent,
            child: Icon(
              controller.value.isPlaying? Icons.pause : Icons.play_arrow
            ),
            onPressed: (){
              setState(() {
                if(controller.value.isPlaying)
                  {
                    controller.pause();
                  }
                else
                  {
                    controller.play();
                  }
              });
            },
          )
        ],
      )
    );
  }
}