Home Blog Page 94

Alert Dialog Box using RFlutter_Alert Package

0
Alert Dialog Box in Flutter App development
Alert Dialog Box in Flutter App development

Hi Guys, Welcome to ‘Proto Coders Point’ in this Post we will learn how to Create a  Alert Dialog in Flutter app development using RFlutter_Alert Library Package.

What is Alert Dialog box?

Alert Dialog Box is basically a Box pop up which display some kind of Message or any action.It is normally used to ask the app user whether he want to continue to next process or discontinue.

Introduction to RFlutter Alert

RFlutter Alert is super customizable and easy to use alert/popup dialog for flutter app development. You may create reusuable alert styles or add buttons.

DEMO GIF

Flutter Alert Dialog
Flutter Alert Dialog

 

Feature of RFlutter Alert

  • Can be implement Single line basic alert
  • Adding buttons dynamically (as much as you want)
  • Predefined beautiful alert styles (success, error, warning, info)
  • Reusable alert styles
  • Super customizable
    • Change animation (fromTop, fromBottom, fromRight, fromLeft, grow, shrink)
    • Set animation duration
    • Show/hide close button
    • Set overlay tap to dismiss
    • Assign Title and desc styles
    • Change dialog border style

Use RFlutter Alert package as a library

Step1:

Add this to your package’s pubspec.yaml file:

dependencies:
  rflutter_alert: ^1.0.3

Step 2 :

Now in your main.dart Dart code, you can use this code to import RFlutter_alert packages:

import 'package:rflutter_alert/rflutter_alert.dart';

Now you are done with importing the RFlutter Alert Library package into your Flutter Application.

Implementation of Flutter Alert dialog box

There are many ways to show a alert dialog box, but in the post will we see 4 customized way to implement Flutter Alert dialog box pop up.

1. easiest way to create RFlutter Alert

The easiest way for creating RFlutter Alert.

This is a snippet code, Complete code for this project will be at the bottom.

Alert(
            context: context,
            title: "RFLUTTER ALERT",
            desc: "Proto Coders Point, Flutter alert dialog box is more awesome with RFlutter Alert.")
        .show();

The easiest way to display a alert dialog box in flutter is that just to display a title with some text in it and a description with some information of message.

easiest way to create RFlutter Alert
easiest way to create RFlutter Alert

This default alert dialog will come up a default cancel button with it to just close the dialog box.

2. Alert with a button in RFlutter Alert

Alert(
      context: context,
      type: AlertType.error,
      title: "RFLUTTER ALERT",
      desc: "Here we are creating a button inside alert box.",
      buttons: [
        DialogButton(
          child: Text(
            "Button",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          width: 120,
        )
      ],
    ).show();
Alert with a button in RFlutter Alert
Alert with a button in RFlutter Alert

Here we are creating a button inside the alert dialog box, the button can be given some action to be performed when onclicked/onPressed.

type: AlertType.error : this will show a cross image.

3. Alert dialog with 2 Button in RFlutter Alert

Alert(
      context: context,
      type: AlertType.warning,
      title: "RFLUTTER ALERT",
      desc: "Alert Dialog with 2 Buttons.",
      buttons: [
        DialogButton(
          child: Text(
            "OK",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          color: Color.fromRGBO(0, 179, 134, 1.0),
        ),
        DialogButton(
          child: Text(
            "Cancel",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          gradient: LinearGradient(colors: [
            Color.fromRGBO(116, 116, 191, 1.0),
            Color.fromRGBO(52, 138, 199, 1.0)
          ]),
        )
      ],
    ).show();

Alert Dialog with 2 Buttons, Here i have created a dialog with 2 button in it. One button is to accept the alert and second button is to decline the alert message.

Alert dialog with 2 Button in RFlutter Alert
Alert dialog with 2 Button in RFlutter Alert

Then, i have also customized the button with gradient color feature.

3. Alert dialog with Login Content in RFlutter Alert

Alert(
        context: context,
        title: "LOGIN",
        content: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                icon: Icon(Icons.account_circle),
                labelText: 'Username',
              ),
            ),
            TextField(
              obscureText: true,
              decoration: InputDecoration(
                icon: Icon(Icons.lock),
                labelText: 'Password',
              ),
            ),
          ],
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "LOGIN",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
Alert dialog with Login Content in RFlutter Alert
Alert dialog with Login Content in RFlutter Alert

Here i have 2 TextField with a Login Button, so that we can show a login required alert dialog box

Complete Flutter Alert Dialog source code

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

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

class RatelApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('RFlutter Alert by Ratel'),
        ),
        body: PopupDialog(),
      ),
    );
  }
}

class PopupDialog extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Basic Alert'),
              onPressed: () => _onBasicAlertPressed(context),
              color: Colors.blue,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Button'),
              onPressed: () => _onAlertButtonPressed(context),
              color: Colors.green,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Buttons'),
              onPressed: () => _onAlertButtonsPressed(context),
              color: Colors.red,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Custom Content'),
              onPressed: () => _onAlertWithCustomContentPressed(context),
              color: Colors.yellow,
              textColor: Colors.black,
            ),
          ],
        ),
      ),
    );
  }

// The easiest way for creating RFlutter Alert
  _onBasicAlertPressed(context) {
    Alert(
            context: context,
            title: "RFLUTTER ALERT",
            desc: "Flutter is more awesome with RFlutter Alert.")
        .show();
  }

// Alert with single button.
  _onAlertButtonPressed(context) {
    Alert(
      context: context,
      type: AlertType.error,
      title: "RFLUTTER ALERT",
      desc: "Flutter is more awesome with RFlutter Alert.",
      buttons: [
        DialogButton(
          child: Text(
            "Button",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          width: 120,
        )
      ],
    ).show();
  }

// Alert with multiple and custom buttons
  _onAlertButtonsPressed(context) {
    Alert(
      context: context,
      type: AlertType.warning,
      title: "RFLUTTER ALERT",
      desc: "Flutter is more awesome with RFlutter Alert.",
      buttons: [
        DialogButton(
          child: Text(
            "Button_1",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          color: Color.fromRGBO(0, 179, 134, 1.0),
        ),
        DialogButton(
          child: Text(
            "Button_2",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          gradient: LinearGradient(colors: [
            Color.fromRGBO(116, 116, 191, 1.0),
            Color.fromRGBO(52, 138, 199, 1.0)
          ]),
        )
      ],
    ).show();
  }

// Alert custom content
  _onAlertWithCustomContentPressed(context) {
    Alert(
        context: context,
        title: "LOGIN",
        content: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                icon: Icon(Icons.account_circle),
                labelText: 'Username',
              ),
            ),
            TextField(
              obscureText: true,
              decoration: InputDecoration(
                icon: Icon(Icons.lock),
                labelText: 'Password',
              ),
            ),
          ],
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "LOGIN",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
  }
}

 

Recommended Articles

Flutter show alert dialog using quickalert package

Flutter Alert Dialog using RFlutter_alert package

Android Custom dialog box

Android Alert Box with list of menu options

Flutter rating dialog – redirect user to app store

How to implement Togglebutton Widget in Flutter App development

3
/home/rajat/Downloads/flutter toggle buttons app development
flutter toggle buttons app development

Hi Guys welcome to Proto Coders Point. In the Post we will learn how to implement a Widget that is a ToggleButton in Flutter App development.

This is How the Final Flutter App Output will look like

flutter app development toggle button
flutter app development toggle button

What is a ToggleButton Widget?

Checked / unchecked (On / Off)  status can be displayed on the button using the a ToggleButton widget. If the user has to change the setting between two states, it is beneficial. On / Off Audio Sound, Wifi etc. In such case we make user of a Togglebutton in web, android or flutter app development.

Implementation of Togglebutton in flutter app development using android-studio.

So lets begin the implementation of ToggleButton, I am using android-studio to build the app.

Learn more about flutter togglebutton class on official site.

Creating a new Flutter Project in android-studio

creating-new-flutter-project-in-android-studio
creating-new-flutter-project-in-android-studio

New > New Flutter Project > Select Flutter Application

Give a name to you flutter app project > select destination path > NEXT

ToggleButton Flutter widget Code.

ToggleButtons(
  children: <Widget>[
    Icon(Icons.ac_unit),
    Icon(Icons.call),
    Icon(Icons.cake),
  ],
  onPressed: (int index) {
    setState(() {
      isSelected[index] = !isSelected[index];
    });
  },
  isSelected: isSelected,
),

Here, we have a ToggleButtons which has children array of widget which consist of 3 Icons, which allows for multiple Buttons to be simultaneously selected.

Complete code for implementation of flutter widget ToggleButtons

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        home: Scaffold(
          backgroundColor: Colors.blueGrey,
          appBar: AppBar(
            title: Text("ToggleButton"),
          ),
          body: MainPage(),
        ));
  }
}

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  List<bool> _selection = List.generate(3, (_) => false);
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ToggleButtons(
        children: <Widget>[
          Icon(Icons.local_cafe),
          Icon(Icons.fastfood),
          Icon(Icons.cake)
        ],
        borderColor: Colors.yellowAccent,
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        borderWidth: 2,
        isSelected: _selection,
        onPressed: (int index) {
          setState(() {
            _selection[index] = !_selection[index];
          });
        },
      ),
    );
  }
}

Output of above code.

toggle button flutter
toggle button flutter

Properties of Flutter ToggleButton.

borderColor : Used to display a border Color when button is selected and unselected.

borderRadius : used to give a circular border to the buttons.

borderWidth : To set the width size of button borderwidth.

borderColor: Colors.grey,
color: Colors.green,
borderRadius: BorderRadius.circular(10),
borderWidth: 2,

selectedColor : Colors.orange : This property will get activated whichever button is been selected.

selectedBorderColor: Colors.white :  This property is used to display a customized border color on the selected button.

There are many other Properties that will help you in Customizing the toggle buttons

Check out the official flutter site to learn more about its properties

 

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

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

Hey guys, welcome to Proto Coders Point. This Tutorial post is all about implementing Android Volley Library Tutorial. I have a URL on our website  that gives me some JSON format data, and by using Volley library we will get those data, and we will also parse it. Ok So if you want to learn how to fetch json data from a URL in android and display it in Listview then let’s start this Android Tutorial on Volley library.

Before Starting Implementation let us know Basic of Volley Library.

What is Android Volley?

If you are new in android then you might be thinking what is this Volley library?

Volley is an HTTP library that makes networking very easy and fast, for Android application development.

What are benefits of  Android Volley?

  • Easy to use request management
  • Fast in fetching data from Any network.
  • Efficient network management
  • Easily customizable according to our need.

Android Tutorial on Volley library Implementation in android Studio.

Demo Output of android volley Library project

android volley library tutorial project
android volley library tutorial project

Now it’s time for implement library, As i have told you above that i have a  URL that contain JSON Data Format.

https://protocoderspoint.com/jsondata/superheros.json

Then if you are implementing this project then you can use same URL for your project Practice or Create your own JSON Data.

If you open the above URL, you will see the following JSON DATA .

{
  "superheros": [
    {
      "name": "Flash",
      "power": "Speed Run :.............."
    },
    {
      "name": "Super Man",
      "power": "the powers of flight, ................."
    },
    {
      "name": "Thor",
      "power": "Superhuman strength, ........"
    },
    {
        "name":"Hulk",
        "power":"Incredible superhuman strength, ......."
    },
    {
        "name":"Vemon",
        "power":"Venom also has super strength — ........"
    }
  ]
}

Now As you can see in above Screenshot Image we have some JSON data. At first, we have a JSON object { }, then inside that object, we have a key name superheros which contain array of JSON objects. Each object in the array has two more keys name and power. So In this android project our task is that to fetch this data and display it into a custom ListView.

Creating a new project under android-studio

As always the basic step in any development if creating a new Project.

when the project is been created successfully, we need to add uses-permission with INTERNET as we are about to perform a network Data fetch operation and it requires internet permission.

Adding internet Permission

Open the AndroidManifest.xml file under you project and  you need to add internet permission as shown below.

For your application to work freely on Android Pie ( 9 ) and above you need to add uses-library org.apache.http.legacy inside application tag

Check out below screenshot for this

uses-library org.apache.http.legacy
uses-library org.apache.http.legacy

Adding Volley Library

This is the very important step. As we are going to use volley library.

adding android volley library
adding android volley library

navigate towords project

Gradle Scripts > build gradle (Module:app) > under dependencies add below lines of codes

dependencies {
    ..................
    ................
    implementation 'com.android.volley:volley:1.1.1'
}

Now, you need to sync your android project and then its done with adding volley library into you project.

Create a Data Model Class

Data Model Class is used to store the fetched data in objects. So create a class named SuperHeros.java and then copy down the below lines of codes.

package protocoderspoint.com.volleyandroidpractices;

public class SuperHero {
    String name, power;

    public SuperHero(String name, String power) {
        this.name = name;
        this.power = power;
    }

    public String getName() {
        return name;
    }

    public String getPower() {
        return power;
    }
}

Creating a UI Design with ListView

  • So i previously  told you that we are going to fetch the data and show the data in a listView. So we are creating a Custom Listview to show data.

Copy paste the below lines of code inside activity_main.xml.

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

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:visibility="gone"
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

As you can see that i have used ProgressBar that because when the fetching of data is going on we can show a progress bar until the data is fetched completed.

Then we would need a layout for our list items.

Inside the layout directory (res->layout)  you need to create a new layout resource file and name it  i have named it as list_items.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/textViewPower"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:textColor="#08308e" />

</LinearLayout>

Here we have two string items i.e (name and power) in our json data, So we created two TextViews here to display the fetched data here.

Creating a Custom Adapter for listview

For this you need to create a new java class,i have named it as ListViewAdapter.java and copy the below code in that java Adapter class .

package protocoderspoint.com.volleyandroidpractices;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class ListViewAdopter extends ArrayAdapter<SuperHero> {

    //the hero list that will be displayed
    private List<SuperHero> superHeroList;

    //the context object
    private Context mCtx;

    //here we are getting the herolist and context
    //so while creating the object of this adapter class we need to give herolist and context
    public ListViewAdopter(List<SuperHero> superHeroList, Context mCtx) {
        super(mCtx, R.layout.list_items, superHeroList);
        this.superHeroList = superHeroList;
        this.mCtx = mCtx;
    }

    //this method will return the list item
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //getting the layoutinflater
        LayoutInflater inflater = LayoutInflater.from(mCtx);

        //creating a view with our xml layout
        View listViewItem = inflater.inflate(R.layout.list_items, null, true);

        //getting text views
        TextView textViewName = listViewItem.findViewById(R.id.textViewName);
        TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewPower);

        //Getting the superHero for the specified position
        SuperHero superHero = superHeroList.get(position);

        //setting superHero values to textviews
        textViewName.setText(superHero.getName());
        textViewImageUrl.setText(superHero.getPower());

        //returning the listitem
        return listViewItem;
    }
}

Now we are in the last part  that is fetching and parsing the json and displaying it to the ListView.

Fetching JSON Data from URL

Open MainActivity.java file  and paste the below lines of code.

package protocoderspoint.com.volleyandroidpractices;


import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //the URL having the json data
    private static final String JSON_URL = "https://protocoderspoint.com/jsondata/superheros.json";

    //listview object
    ListView listView;

    //the hero list where we will store all the hero objects after parsing json
    List<SuperHero> superHeroList;

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

        //initializing listview and hero list
        listView = (ListView) findViewById(R.id.listView);
        superHeroList = new ArrayList<>();

        //this method will fetch and parse the data
        loadHeroList();
    }

    private void loadHeroList() {
        //getting the progressbar
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //making the progressbar visible
        progressBar.setVisibility(View.VISIBLE);

        //creating a string request to send request to the url
        StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //hiding the progressbar after completion
                        progressBar.setVisibility(View.INVISIBLE);
                        Log.d("Json Response",response);


                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);

                            //we have the array named hero inside the object
                            //so here we are getting that json array
                            JSONArray heroArray = obj.getJSONArray("superheros");

                            //now looping through all the elements of the json array
                            for (int i = 0; i < heroArray.length(); i++) {
                                //getting the json object of the particular index inside the array
                                JSONObject heroObject = heroArray.getJSONObject(i);

                                //creating a superHero object and giving them the values from json object
                                SuperHero superHero = new SuperHero(heroObject.getString("name"), heroObject.getString("power"));

                                //adding the superHero to herolist
                                superHeroList.add(superHero);
                            }

                            //creating custom adapter object
                            ListViewAdopter adapter = new ListViewAdopter(superHeroList, getApplicationContext());

                            //adding the adapter to listview
                            listView.setAdapter(adapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        //creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //adding the string request to request queue
        requestQueue.add(stringRequest);
    }
}

 

What is the future of flutter? is their any scope in flutter development ?

0
What is the Future of flutter development
What is the Future of flutter development

In my sincere opinion – future seems shiny bright for Flutter. Time is ripe for alternate.

Java/Kotlin and Swift/objective-C lets in one to broaden handiest for Android and iOS respectively when it comes to developing apps.

however, Flutter framework opens doorways to cross-platform improvement surroundings. for this reason, very quickly human beings would want emigrate to a greater versatile platform, subsequently Flutter would upward thrust to glory.

future of flutter app developer
future of flutter app developer

Tutorial I Purchased to learn Flutter – future

For getting to know app improvement, I followed more than one blogs, diverse Flutter programming and books, few video tutorials – both paid and loose.

However none could may want to make my sail a clean experience. It changed into only in March 2019 that I landed up on a video direction that modified the entirety for proper and brought me to pen this answer.

those who are searching ahead to learning cross-platform app development, i am bringing up the link to the course that helped me come to be an App Developer, you may locate it useful – The Complete 2020 Flutter Development Bootcamp with Dart

 

Which i have personally purchased and learn a lot about cross-platform app development as it as the future of flutter.

What you’ll learn in this flutter udemy course?

  •  fast and native-quality apps with Flutter Build beautiful,
  • Become a fully-fledged Flutter developer
  • Build Android and iOS apps with just one codebase
  • Android and iOS apps building using just one programming language (Dart)
  • You can build a portfolio of  Flutter apps to impress any Job recruiter
  • You will easily Understand all the fundamental concepts of Flutter Apps development
  • Become proficient in one of the fastest growing technologies

What is the future scope of Flutter?

I guess that the future scope is to become a successful cross-platform environment flutter for building great mobile apps for iOS, Android.

You want to be aware that for a brand new project like Flutter some things may want more work due to the fact no ready-to-use packages are to be had, however the Flutter community is quite energetic and new packages are added every day to Dart Package and i expect the frequency to growth loads when Flutter 1.0 will be release in all likelihood inside the no longer too far destiny.

Check out how to install flutter

If you are ubuntu user check how to install flutter in ubuntu

Infinite Cycle View Pager – GithubAndroid Library Dev Light

1
infinite cycle view pager android github library
infinite cycle view pager android github library

In this tutorial i will show you how to make an Infinite Cycle View Pager with On Click Listner.

INFINITE CYCLE VIEW PAGER

Demo Screen Recorded

This Github Android Library  comes with with two-way orientation i.e Horizontal and Vertical Orientation and interactive effect.

In a normal ViewPager, you are allowed only  to scroll from the first page to second page until the last Page, from left-to-right. Once you reach the last page, your only option is to scroll backwards, right-to-left. In other words if we say from last page you cannot go back to first page directly, you need to scroll backwards until first page. Therefore I have found a infinite cycle ImageView Card ViewPager that solve the a problem.

Installation of Infinite Card ViewPager in project.

Let us now start adding required dependencies library into our android studio project.

Minimun SDK Version required for this library:

InfiniteCycleViewPager requires a minimum SDK version of 11.

Add Github Dependenices library in to Gradle (Module:app)

implementation 'com.github.devlight:infinitecycleviewpager:1.0.2'

Or Maven:

<dependency>
  <groupId>com.github.devlight</groupId>
  <artifactId>infinitecycleviewpager</artifactId>
  <version>1.0.2</version>
  <type>pom</type>
</dependency>

Library is now been successfully added into your project.

activity_main.xml

<!--<com.gigamole.infinitecycleviewpager.VerticalInfiniteCycleViewPager-->
<com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:icvp_interpolator="..."
    app:icvp_center_page_scale_offset="30dp"
    app:icvp_max_page_scale="0.8"
    app:icvp_medium_scaled="true"
    app:icvp_min_page_scale="0.5"
    app:icvp_min_page_scale_offset="5dp"
    app:icvp_scroll_duration="500"/>

Refer Official Github library

Implementation of Infinite Cycle ViewPager Github Android Library.

Create a new Project under Android Studio

File>New>New Project > Emply Project > Give name To the prject.

activity_Main.xml

Add the xml UI design code of  Horizontal Infinite Cycle ViewPager.

You can set vertical or horizontal infinite cycle ViewPager.

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

    <com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager
        android:id="@+id/horizontalcardviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:icvp_interpolator="@android:anim/accelerate_decelerate_interpolator"
        app:icvp_center_page_scale_offset="30dp"
        app:icvp_max_page_scale="0.8"
        app:icvp_medium_scaled="true"
        app:icvp_min_page_scale="0.5"
        app:icvp_min_page_scale_offset="5dp"
        app:icvp_scroll_duration="500">
    </com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager>

</RelativeLayout>

Then, Create a new Layout xml file under Layout directory.

Right Click on Layout directory > New > Layout Resource File

I have name new layout xml file as card_item.xml

In card_item.xml file we will define the UI design.

Card_item.xml

<?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:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:id="@+id/fragment"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/imageview"/>

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textColor="#F1EDED"
           android:id="@+id/textview1"
           android:text="HELLO WORLD"
           android:textSize="30sp"
           android:layout_margin="20dp"
           android:layout_gravity="bottom"
           />
    </FrameLayout>
</LinearLayout>

In the above lines of code i have 2 views that is  ImageView and a TextView which is inside FrameLayout

I have wrapped it into FrameLayout so that i can display a textview top of ImageView.

MyAdopter.java

package protocoderspoint.com.devlightinfinitecardviewpager;

import android.content.Context;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public class MyAdopter extends PagerAdapter {

    List<Integer> images;
    Context context;
    LayoutInflater layoutInflater;


    public MyAdopter(List<Integer> images, Context context) {
        this.images = images;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return images.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

        container.removeView((View)object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {

        View view= layoutInflater.inflate(R.layout.card_item,container,false);
        ImageView imageView =(ImageView)view.findViewById(R.id.imageview);
        imageView.setImageResource(images.get(position));
        container.addView(view);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"Clicked image " +position,Toast.LENGTH_LONG ).show();
            }
        });
        return view;

    }
}

Create a new Java class and name it as MyAdopter.java and copy paste the below adopter code in that class.

MainActivty.java

package protocoderspoint.com.devlightinfinitecardviewpager;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.HorizontalScrollView;

import com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<Integer> images= new ArrayList<>();

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


        initData();

        HorizontalInfiniteCycleViewPager horizontalInfiniteCycleViewPager =(HorizontalInfiniteCycleViewPager)findViewById(R.id.horizontalcardviewpager);
        MyAdopter myAdopter = new MyAdopter(images,getBaseContext());
        horizontalInfiniteCycleViewPager.setAdapter(myAdopter);
       

    }

    private void initData() {
        images.add(R.drawable.card1a);
        images.add(R.drawable.card2a);
        images.add(R.drawable.card3a);
        images.add(R.drawable.card4a);
    }
}

MainActivity.java is a main launcher page that will load as soon as the app start.

List that holds arrayList of images from drawable directory.

images.add(R.drawable.card1a) is used to add images into arraylist.

Just Copy paste above code in Main_Activity.java

and all set the Infinite Cycle View Pager android project is ready to run.

How to Implement Webview in flutter? – Load website in flutter webview plugin

1
Flutter WebView
Flutter WebView

Hi Guys Welcome to Proto Coders Point, This project is a Beginner starting point for a Flutter application, Here we will see how can we implement webview in flutter web app development using webview plugin.

Demo on Flutter Webview

"<yoastmark

Video Tutorial – Convert Website to app

Introduction on Flutter WebView 

Presenting a web view is pretty common in mobile apps. In Flutter, this is done by using the webview_flutter package.

Use this package Webview_Flutter as a library

If you want to use flutter webview widget you need to add some dependencies

Add this to your package’s pubspec.yaml file:

dependencies:
  webview_flutter: ^0.3.15+1

Then make sure with this indentation, sight empty space in pubspec.yaml file might give you error.

Import flutter webview widget package

Now in your Dart code (main.dart), you need to import  widget packages, so that you can use flutter webview in you class file.

import 'package:webview_flutter/webview_flutter.dart';

Let’s start implementing webview in your flutter application.

Create a new Flutter project  in android studio.

creating-new-flutter-project-in-android-studio
creating-new-flutter-project-in-android-studio

Give a name to your flutter application. in my case i have name it as flutter_webview. you can name it anything it left to you.

So our flutter project is build and ready to implement our flutter code.

But then are flutter default code added into our flutter dart code. you can delete all the code from main.dart class and copy paste the code i provide you below.

Add below code in your project

Webview widget snippet

WebView(
          key: Key("webview"),
          initialUrl: flutterUrl,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController)
          {
            _controller = webViewController;
          },

First, the key parameter allows the Flutter widget tree to refer to this widget easily using a unique key created via Flutter’s UniqueKey() method you’ll soon see in the full example below.

javascriptMode simply allows us to control what kind of Javascript can be run in our web view.

Finally, initialUrl is the URL we want to display.

The important gotcha here is that we’ll need to use a StatefulWidget because it appears that if we use a StatelessWidget, the WebView will not load properly.

We pass in a url parameter to this widget, which is used in the state of our StatefulWidget.

Full flutter webview source Code

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var title = 'Webview Demo';
    return new MaterialApp(
      title: title,
      home: new MyAppHomePage(),
    );
  }
}

class MyAppHomePage extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

const String flutterUrl = "https://flutter.dev/";
const String wikiUrl = "https://es.wikipedia.org";

class _MyAppState extends State<MyAppHomePage> {
  WebViewController _controller;

  _back() async {
    if (await _controller.canGoBack()) {
      await _controller.goBack();
    }
  }

  _forward() async {
    if (await _controller.canGoForward()) {
      await _controller.goForward();
    }
  }

  _loadPage() async {
    var url = await _controller.currentUrl();
    _controller.loadUrl(
      url == "https://flutter.dev/"
          ? 'https://es.wikipedia.org'
          : "https://flutter.dev/",
    );

    print(url);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WebView'),
        actions: <Widget>[
          IconButton(
            onPressed: _back,
            icon: Icon(Icons.arrow_back_ios),
          ),
          IconButton(
            onPressed: _forward,
            icon: Icon(Icons.arrow_forward_ios),
          ),
          SizedBox(width: 10),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _loadPage,
        child: Icon(Icons.refresh),
      ),
      body: SafeArea(
        child: WebView(
          key: Key("webview"),
          initialUrl: flutterUrl,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller = webViewController;
          },
        ),
      ),
    );
  }
}

In the app bar I have used 2 icons that will function as a back and forword button when we navigate to some other url in out webview onWebView controller will take care of this process.

Here there is also a reload button i.e floatingActionButton that will reload the initial url of the application.

Hope this article was useful for you project.

keep visiting proto coders point

Recommended Post

check out how to add bottomNavigationbar

profile page UI Design 

Android – How to Convert Website into Android App ?