So Now we have done with learning basic information about this widget.
Now it’s time to implement the Cupertino Action sheet Widget.
As usual you need to create a new Flutter project, or implement it in your existing flutter project it your choice.
So I am using Android-studio to create a new flutter Project.
File> New > New Flutter Project
Fill are the required staff.
Create a RaisedButton that can activate CupertinoActionSheet
As you Flutter Project is ready you need to remove all the existing flutter code that is been by-default added into your project by Google flutter team.
I Assume that you have removed all the default flutter code. Ok
Then, you need to create a RaiseButton inside body tag as displayed in below snippet Flutter code.
body: Center(
child: RaisedButton(
onPressed: () {
//Cupertino Action sheet will come over here
},
child: Text("Click me "),
),
),
Here, i have a center widget that will bring all the widget at the center of the screen, Here there is a child widget RaisedButton that simply create a button widget at the center of the body tag.
RaisedButton have a Function method onPressed that triggers when the user click on Raised Button.
CupertinoActionSheet Snippet Code
Then here, i have a CupertinoActionSheet with a title that simply display a text, and Message that display the description of the popup menu.
Then, i Have actions widget that is simply a array list of Cupertino Option Menus
In the Below Snippet code i have created 2 actions button that can perform different actions.
isDefaultAction: is set to true because the action button text will be displayed with blue color.
isDestructiveAction: is set to true that display action button text in red color.
CupertinoActionSheet(
title: Text("Cupertino Action Sheet"),
message: Text("Select any action "),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Action 1"),
isDefaultAction: true,
onPressed: () {
print("Action 1 is been clicked");
},
),
CupertinoActionSheetAction(
child: Text("Action 2"),
isDestructiveAction: true,
onPressed: () {
print("Action 2 is been clicked");
},
)
],
);
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(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MainPage(),
);
}
}
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cupertino Action sheet demo"),
),
body: Center(
child: RaisedButton(
onPressed: () {
final action = CupertinoActionSheet(
title: Text(
"Proto Coders Point",
style: TextStyle(fontSize: 30),
),
message: Text(
"Select any action ",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Action 1"),
isDefaultAction: true,
onPressed: () {
print("Action 1 is been clicked");
},
),
CupertinoActionSheetAction(
child: Text("Action 2"),
isDestructiveAction: true,
onPressed: () {
print("Action 2 is been clicked");
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(
context: context, builder: (context) => action);
},
child: Text("Click me "),
),
),
);
}
}
In this Tutorial, we will Implement Flutter Fancy Bottom Navigation Baranimation using android-studio to write flutter Dart codes.
Then, Check out the below Image that shows you how exactly does the flutter Fancy Bottom Navigation Bar looks like.
FANCY Flutter BOTTOM Navigation Bar AMINATION
Demo
Flutter fancy Bottom Navigation bar
Instead, you’re switching out a over all group of content within a single page to give the appearance that the page is changing.Here is a illustration to visually describe what we’re doing. Not that the overall “scaffolding”, as Flutter calls it, stays the same and the contents within the page change.
As usual you need to create a new Flutter Project to implement the above.
File >New > New Flutter Project
First We need to start by changing the MyApp widget in main.dart to be a Stateful widget. We need to do this because we will be storing which tab the user is currently on within our state.
Not to Worry in our project we are simple calling StateFullWidget class from StatelessWidget
It might seem to be little confusing for beginner learn of flutter but no need to worry the complete code will given below in the end of this post.
Adding fancy_bottom_navigation dependencies into your project
Here on the right side of your android studio you will see your flutter project
All the above page contain simple Text which is child of Container() widget in turn Container is the child if Center() widget,with simple show a text at the center of screen.
A TabData Contains a iconData -> which is used to show a icon on the tab with some title.
onTabChangeListener this function will simple keep track of which tab is currently open. and listens to which tab this click.
Optional Usage for customizing the Bottom Navigation Bar Tabs
initialSelection -> Defaults to 0
circleColor -> Defaults to null,
activeIconColor -> Defaults to null,
inactiveIconColor -> Defaults to null,
textColor -> Defaults to null,
barBackgroundColor -> Defaults to null, derives from
key -> Defaults to null<br/>
Theme Customizing
To learn more about this Flutter widget Library refer Official site
Complete Code of Flutter Fancy Bottom Navigation Bar
main.dart
Just copy paste the below lines of flutter code under main.dart file which will show you flutter fancy bottom Navigation bar at the bottom of the screen through which you can easily navigate to different pages being at the same page.
Here, currentPage is set to 0 and pageOption is a array of different pages available
and body of flutter app is set to current page like pageOption[currentPage] with simple loads Home page when we run the app first
By making use of onTabChangedListener we are changing currentPage value to tab the tab value which is been clicked as that tabed page gets loaded on the screen.
Ok the main think is here i.e
The flutter widget package library have some Limitation
So total tabs that can be implemented using this widget is ranged from 2-4 tabs.
Base Adapter android is simple a base class that is used in implementation of any Adopter that can be used in variour activity in android like ListView or GridView.
So In this Article we need Customize the GridView by creating our own Custom Adopter that extends BaseAdopter
Below is the example of GridView in Android, In which we show the Android Version logo’s in the form of Grids.
Gridview in Android using Base Adopter
Step1: Create a new Android project in Android Studio as usually and you need to fill all the required details.
In our case we have named GridView Using Base Adopter and package protocoderspoint.com.griviewbaseadopter
GridView Using Base Adapter
Step 3 : Now, Just Open activity_main.xml design and paste the below xml code in that file.
Here i have created a GridView with have set with number of columns as 3.
<?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:orientation="vertical">
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:padding="1dp"
android:layout_margin="10dp"
android:numColumns="3" /> <!-- GridView with 3 value for numColumns attribute -->
</LinearLayout>
Step 3: : Ok then Create a new XML file I have named the new file as gridview_image.xml. because we are just displaying a Image using ImageView and a Text with TextView.
Then the CustomAdopter to set the andorid version logo images.
Then Here you need to download come images and paste it into drawable folder of your android project.
Keep in mind that image size should not be more then 2 mb else the app might force stop.
Now, Name all the images as logo1,logo2 and so on.
Step 5: Create a new class CustomAdapter.java and paste the below code.
CustomAdopter.java
Then, Now We have to create a CustomAdopter.java class That is Extends BaseAdapter in it.
In CustomAdopter we will set image logo’s and set it’s text under the imageview logo.
package protocoderspoint.com.gridviewusingbaseadapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
Context context;
int logos[];
LayoutInflater inflter;
String title[];
public CustomAdapter(Context applicationContext, int[] logos,String[] text) {
this.context = applicationContext;
this.logos = logos;
inflter = (LayoutInflater.from(applicationContext));
this.title=text;
}
@Override
public int getCount() {
return logos.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.gridview_image, null); // inflate the layout
ImageView icon = (ImageView) view.findViewById(R.id.icon); // get the reference of ImageView
icon.setImageResource(logos[i]); // set logo images
TextView textView = (TextView)view.findViewById(R.id.text1);
textView.setText(title[i]);
return view;
}
}
Step 6 : Copy below code in Main_Activity.java
package protocoderspoint.com.gridviewusingbaseadapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
GridView simpleGrid;
int logos[] = {R.drawable.logo1, R.drawable.logo2, R.drawable.logo3,R.drawable.logo4,R.drawable.logo5,R.drawable.logo6,R.drawable.logo7,R.drawable.logo8};
String title[]={"Cup Cake","Donut","Eclair","Froya","Gingerbread","Kitkat","Lollipop","And Much More"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleGrid = (GridView) findViewById(R.id.simpleGridView); // init GridView
// Create an object of CustomAdapter and set Adapter to GirdView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), logos,title);
simpleGrid.setAdapter(customAdapter);
// implement setOnItemClickListener event on GridView
simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// set an Intent to Another Activity
Intent intent = new Intent(MainActivity.this, activity_second.class);
intent.putExtra("image", logos[position]); // put image data in Intent
startActivity(intent); // start Intent
}
});
}
}
All is set and app is ready that display girdview with images in 3 columns but when its is clicked i need to open second activity to open which simply shows the image with the gridview image is been clicked
Step 7: Now Create a new Activity with name activity_second.class.
To create new Activity just follow this steps :
Right click of Project > New >Activity > Empty Activity
And name it as activity_second, this will create both java file as well as xml file
Step 8: Open Second Actvity xml file and copy paste below code, Our Second Activity to display the android version logo image in full size, by which gridView imageis been clicked.
Step 9: Now Open a new Activity that we have created just with name activity_second.java and add below code in it.
package protocoderspoint.com.gridviewusingbaseadapter;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
public class activity_second extends AppCompatActivity {
ImageView selectedImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
selectedImage = (ImageView) findViewById(R.id.selectedImage); // init a ImageView
Intent intent = getIntent(); // get Intent which we set from Previous Activity
selectedImage.setImageResource(intent.getIntExtra("image", 0)); // get image from Intent and set it in ImageView
}
}
Android Registration Tutorial PHP MySQL using HttpURLConnection class
As you may know that Google Android has deprecated it support for Apache module i.e (HttpPost and HttpGet and HttpClient and many more class that has Apache module) since API level 22, Now the alternate way is to use JAVA’s HttpURLConnection Class.
This tutorial depicts the Android Registration form to deal with GET and POST data using HttpURLConnection class.
So then lets us start implementing a Registration form in android that stores data into MySQL phpmyadmin database using HttpURLConnection class.
Step 1: Creating a database in Phpmyadmin dashboard
if i say, I am making use of localhost to work with phpmyadmin MySQL service. you can use any of your hosting either webhosting which has phpmyadmin installed or your localhost that has WampServer installed.
how to create database in phpmyadmin
then, login into your phpmyadmin dashboard and and create a new Database,
I have created a database name Coders (just for this tutorial) you can specific any name for that database.
CREATE DATABASE databasename;
now, database is ready it time to create table names as register.
There are 2 ways for creating table in phpmyadmin
1st way
CREATE TABLE Coders (
id int NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
city varchar(20) NOT NULL,
phone varchar(12) NOT NULL,
CONSTRAINT Coders PRIMARY KEY (id)
);
2nd way
the second way for creating table is using phpmyadmin dashborad
In Registration table i have for data entries where i can store data values
id: which is simple a integer value that simple store numbers that i have defined a auto increment and primary key value.
name: which stored name of the user.
city: holds place of the user.
phone: holds mobile number of the user.
All set on server side work.
Step 2 : Php code that handle storing data that if recieved from android app
conn.php
<?php
$db_name="Coders"; // database name
$mysql_username="replace with your login id";
$mysql_password="replace with your password";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
if($conn)
{
//echo "Connection Success";
}
else
{
//echo "Connection Failed";
}
?>
Connection php page is user to get connected to phpmyadmin database
$db_name=”Coders”; // database name
$mysql_username=”replace with your login id”; username that you use to login in to phpmyadmin server
$mysql_password=”replace with your password”; password that you use to sign in.
$server_name=”localhost”; use localhost if you have phpmyadmin installed in you system or else use you doman name or IP address.
registration php code page is use to get data from android code and send it to phpmyadmin to store that data recieved into database.
EG: $fname=$_POST[‘name’]; : data will be recieved from android application to php code
insert query : insertion query will be run to store the recieved data in database.
Step 3 : android studio implementing httpURLConnection class
This Android Php project contains two android activities, MainActivity.java and SuccessActivity.java.
MainActivity is actual Registration form where you can register himself using name,city and phone number and a submit button when clicked the user get registered
SuccessActivity is a plain activity form which simple show a success message of the user screen when the registration is been successfully done.
Snippet code of how to use HttpURLConnection class in andoid
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
MainActivity.java
The complete java code is below
package protocoderspoint.com.localhostphpmyadmin;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.client.ClientProtocolException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button Submit;
EditText name,city,phone;
ProgressDialog pdDialog;
String URL_REGISTER="http://192.168.0.10/protocoderspoint/register.php";
String sname,scity,sphone;
String URL_RESPONSE="";
HttpURLConnection conn;
URL url = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.name);
city=(EditText)findViewById(R.id.city);
phone=(EditText)findViewById(R.id.phone);
Submit=(Button)findViewById(R.id.submit);
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sname = name.getText().toString();
scity = city.getText().toString();
sphone=phone.getText().toString();
Log.d("text",sname+scity+sphone);
new user_register().execute();
}
});
}
public class user_register extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pdDialog = new ProgressDialog(MainActivity.this);
pdDialog.setMessage("Registering user Please Wait..");
pdDialog.setCancelable(false);
pdDialog.show();
}
@Override
protected String doInBackground(Void... arg0) {
try {
URL url = new URL(URL_REGISTER);
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println("name:"+sname);
System.out.println("city:"+scity);
System.out.println("phone:"+sphone);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("name", sname)
.appendQueryParameter("city", scity)
.appendQueryParameter("phone",sphone);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
}else{
return("unsuccessful");
}
}
catch (ClientProtocolException e)
{
Log.d("BLOOD","IOE response " + e.toString());
// TODO Auto-generated catch block
URL_RESPONSE="ERROR";
}
catch (IOException e)
{
Log.d("BLOOD","IOE response " + e.toString());
// TODO Aut return 0
URL_RESPONSE="ERROR";
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pdDialog.isShowing())
pdDialog.dismiss();
String trim_result=result.trim();
Toast.makeText(MainActivity.this, result.trim(), Toast.LENGTH_LONG).show();
if(trim_result.equalsIgnoreCase("true"))
{
/* Here launching another activity when login successful. If you persist login state
use sharedPreferences of Android. and logout button to clear sharedPreferences.
*/
Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
startActivity(intent);
MainActivity.this.finish();
}else if (result.equalsIgnoreCase("false")){
// If username and password does not match display a error message
Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
}
On Submit Button pressed user_register function trigged.
user_register that extends AsyncTask, Asynctask is very useful when it comes to handing any process that runs of background.
onPreExecute(): used to show progressDialog on the screen.
doInBackground(): The sending and recieving data from android registration app and to php file using HttpURLConnection class.
onPostExecute(): this will get execute as soon as doInBackground() task gets completed, here we just disable progressDialog box and and get response from server in teams of true or false, which means registration is successful or unsuccessful.
Then,now the App will successfully run on android 7 and below but when it comes to run on android 8 and above you may face error like:
Error 1 : D/NetworkSecurityConfig: No Network Security Config specified, using platform default
Error 2 : IOE response java.io.IOException: Cleartext HTTP traffic to 192.168.0.10 not permitted
Hi Guys, welcome to Proto Coders Point in this Tutorial will we Learn How to Implement Flutter Slider with show Value.
What is Flutter Slider
A Slider in flutter app development is a Material Design , that is basically used in selecting a range of values.
A slider can be used to select from either a continuous or a discrete set of values. The default is to use a continuous range of values from min to max. To use discrete values, use a non-null value for divisions, which indicates the number of discrete intervals. For example, if min is 0.0 and max is 50.0 and divisions is 5, then the slider can take on the discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
Here are the terms for the parts of a Flutter slider are:
A “thumb”, is a Round shape that help the user to slide horizontally when user what to change in some values.
“track”, is a horizontal line where the user can easily slide the thumb.
The “value indicator”, which is a shape that pops up when the user is dragging the thumb to indicate the value being selected.
The “active” side of the slider is the side between the thumb and the minimum value.
The “inactive” side of the slider is the side between the thumb and the maximum value.
So Let’s Begin the Implementation of Flutter Code with show values.
Implement Flutter Slider with show value
First of all with is very much common, your need to create a new Project or Open an existing project where you want to implement Flutter slider. So i am using android-stdio as my Development Toolkit.
New > New Flutter Project > Give a Name to the project and finish
Then, as soon as new Flutter project is been created, Flutter team have already set a default code that simple counts the number of time the floatingbutton is been pressed.
So, I recommend remove all the code persent in lib > main.dart file and copy paste the below code in it.
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 Slider',
home: MyHomePage(title: 'Flutter Slider Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Demo on Flutter Slider',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w500),
),
],
),
),
);
}
}
Note: The above code is not the complete working of Flutter project, it’s a way to clean all the default code.
The Final Code of complete working Flutter Slider is at the bottom on this Tutorial, you can just copy paste it in main.dart.
Slider comes with Various Properties
As i said Flutter Slider comes with Various Properties that help Flutter Developer to Customize the slider.
Step 5 : Create Firebase In-App Messaging Campaign in the Firebase Console
Now, Go to Your Firebase Console and create a Campaign to show Free In-app Messages.
Firebase Console > Right sidebar GROW > Select In-app Messaging > Create your first Campaign
firebase in app messaging services campaign
Here you will find a option to Test on Device where you can easily run on your test device for testing purpose
Test on device firebase
Then, To get Instance Id you need to run the project in physical device or emulater device so that firebase can generate a Instance ID for testing purpose.
Now, your app is been build successfully and is running on the device.
Navigate to Logcat at the bottom of Android Studio and search for ” Instance “, you will get the instance ID generated by firebase for texting, The instanse ID will look something like this :
I/FIAM.Headless: Starting InAppMessaging runtime with Instance ID " esfS9Au1vYw "
Then, Copy the Instance ID and paste it into Firebase console test on device.
test on device instance id Firebase
and then , Hit the Test button.
after that close the app if running and re-open the app.
Now, you will be able to see Firebase In-app Message been poped up as below.