Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with a latest product called “VELOCITY X” Library developed using Flutter SDK by Pawan Kumar.
What is Flutter Velocity X?
The Velocity X library in flutter development is a minimalist flutter framework that helps you in building custom Application design Rapidly.
Velocity X comes with various properties that we can apply to our flutter widget such as Color, Padding, Text , Box, Card, SizedBox and many more.
Installation of Velocity X in Flutter Project
Step 1: Adding Dependencies
Add the following dependencies in your pubspec.yaml file.
dependencies:
velocity_x: ^0.2.0 // add this line
Step 2: Importing the VelocityX package
Once you have added the velocityx dependencies, Now you can use them in your dart code (main.dart), just by importing the package / component that are required for application development.
Eg: In my case i have imported it in main.dart file
import 'package:velocity_x/velocity_x.dart' ;
Then, it’s all set your flutter project is ready to make use of velocityx librarys.
Tutorial on Applying VelocityX to Text / How to use Velocity X in Text Widget.
This Library gives super power to Text
Note : When are are done with applying velocityx properties to widget or string end it with .make() to make it back to flutter widget.
Converting String Variable to Text Widget
'Demo On Flutter Velocity X'
.text
.size(30)
.bold
.make(),
output
the above code will change the normal String text into text widget, when you define it with .text and at the end convert it to Text widget using .make().
FontStyle
Applying font Style italic
Text('You have pushed the button this many times:',)
.text
.red600 //text color to red
.italic //stlying italic
.make(), // make it as widget
Applying text utilities with UPPERCASE, lowercase, Capitalize and hidePartial
"Text Utilities".text.uppercase.make(), //change the font text to upper case
uppercase – WELCOME TO PROTO CODERS POINT
lowercase – welcome to velocityx
capitalize – Welcome To Velocityx
Hiding Text
you can even hide some text from a long string, Hidden text will be shown in *****
"Text Utilities hidden".text.hidePartial.make(), //this will hide some text from start
hidePartial – ***** To Velocityx
All properties Together
Text("Velocity_X text property all together")
.text
.orange400 // text color orange
.xl // text font extra large
.bold // make text bold
.center //align to center
.heightLoose
.underline // under line to text
.wide // space between text
.uppercase //make text to UPPERCASE
.make(), //convert it back to a widget
So let’s begin implementing this Android FCM project.
Step 1: Create a new Android Project
As usual create a new android project in your android studio
File > New > New Project
Give a name to your project say Firebase push notification service.
Step 2: Connect new Project to firebase using firebase android studio assistant
Step 1: Add Firebase Analytic
tools > firebase > select analytics
1. Connect to firebase
Hit that connect to firebase Button under assistant, This will open default browser with a firebase url to add your android project to your firebase console.
Just agree all the steps on your browser, if you face any problem to connect to firebase console check out the above video
2. Add Analytics to your app
just click on the button suggested by assistant “add analytic to your app” this will add all the required dependencies & classes.
3. Add analytic code
open MainActivity.java basically you loading or first screen of your android app.
private FirebaseAnalytics mFirebaseAnalytics;
//inside of onCreate
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Step 2: Add Cloud Messaging dependencies through assistant
under the android firebase assistant search for cloud messaging under that hit “Add FCM to your app”
This will add the FCM dependencies to your android project.
Step 3: Create a new Service class for FCM Services
Create a service java (Right Click) > New > Service > service and name it a anything your wish in my case i have named it as FirebaseCloudMessagingService.java
Then, Add the below links of notification service codes.
FirebaseCloudMessagingService.java
package com.protocoderspoint.sendingpushnotificationusingphpcode;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseCloudMessagingServices extends FirebaseMessagingService {
public FirebaseCloudMessagingServices() {
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle(); // will hold FCM Title
String message = remoteMessage.getNotification().getBody(); //will hold FCM message body
sendNotification(title,message);
}
}
private void sendNotification(String title, String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "admin_channel_1";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Sample Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
//.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(title)
.setContentText(message);
notificationManager.notify(1, notificationBuilder.build());
}
}
Step 4: Add Volley Library
As we gonna make a call to our php script to send notification in am making use of Volley library to make a call to my service side php code
open build.gradle(app level) and all the following volley dependencies.
implementation 'com.android.volley:volley:1.1.0'
Step 5: Register/ Subscribe to Topic in java code
This is how we make the user to register or subscribe to particular topic so that we can send notification to selected topic or subscriber using the topic that user are registered too.
Snippet code to make user subscribe to a topic in FCM.
Now, open strings.xml and add the following array strings
strings.xml
<resources>
<string name="app_name">Sending PushNotification using php code</string>
<string name="topic_selection">Choose a category: </string>
<string-array name="product_topics">
<item>PC</item>
<item>Laptop</item>
<item>Gadgets</item>
</string-array>
</resources>
ok Then, Let’s design the UI of the app
acitivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<Button
android:id="@+id/subscribe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subscribe on Topic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.269" />
<Spinner
android:id="@+id/spinner"
android:layout_width="409dp"
android:layout_height="80dp"
android:layout_marginTop="64dp"
android:entries="@array/product_topics"
android:gravity="center"
android:prompt="@string/topic_selection"
app:layout_constraintBottom_toTopOf="@+id/subscribe"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.685" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="22dp"
android:text="You will get notified on selected topic only"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/subscribe" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select a Firebase topic to get subscribed on particular topic only"
app:layout_constraintBottom_toTopOf="@+id/spinner"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/getnotified"
android:layout_width="247dp"
android:layout_height="51dp"
android:layout_marginTop="276dp"
android:text="Notify Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Below button will call the php code that sends notification \n to Cloud messaging service topic you are subscribed to"
app:layout_constraintBottom_toTopOf="@+id/getnotified"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.84" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.protocoderspoint.sendingpushnotificationusingphpcode;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
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 com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
Spinner spinnerTopic;
Button subscribe,send_Pushnotification;
// this link is my server where my php script for push notification exist
String URL_NOTI="https://protocoderspoint.com/php/push_notification.php";
String topic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
spinnerTopic = (Spinner)findViewById(R.id.spinner);
subscribe=(Button)findViewById(R.id.subscribe);
send_Pushnotification=(Button)findViewById(R.id.getnotified);
subscribe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
topic = spinnerTopic.getSelectedItem().toString();
System.out.println(topic);
//subscribing yourself to topic you have selected from spinner
FirebaseMessaging.getInstance().subscribeToTopic(topic);
Toast.makeText(MainActivity.this,"Subscribed successfully to: "+topic,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,"Now just Hit Notify me Button "+topic,Toast.LENGTH_SHORT).show();
}
});
send_Pushnotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Send_Notification(topic);
}
});
}
private void Send_Notification(final String topic)
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_NOTI,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("farmerorderdataresponse",response);
try{
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Login Error !1"+e,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Login Error !2"+error,Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("title","Order Received");
params.put("body","This is a notification");
params.put("topic",topic);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
Step 5: network configuration for android version 9
then you need to add a network configuration xml file where you define the network that you will be using…Usually the domain
res (right click) > New > Directory
give new diretory name as “xml”
Then, right click “xml directory” > New > xml resource file and name it as network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
//replace the domain name with your server domain name
<domain includeSubdomains="true">protocoderspoint.com</domain>
</domain-config>
</network-security-config>
Then, where you go your app is ready to subscribe to selected topic using Spinner and will be able to recieve push notification on particular topic the app user is subscribed too firebase cloud messaging service.
Hi Guys, Welcome to Proto Coders Point, if you have seen our last post on how to make an android http request call using okhttp android library, where we have just fetched data from the API which is in JSON format, and just displayed the response.body() in text view.
In this Tutorial post we will show/display the data received by okhttp call a http response data in Simple Listview Adapter.
So to so open AndroidManifest.xml file and the <user-permissioon> Internet.
Snippet code to GET data from URL
OkHttpClient client = new OkHttpClient();
String url = "your api link here";
Request request = new Request.Builder()
.url(url) //request for url by passing url
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if(response.isSuccessful())
{
// task after data is received
}
}
});
OkHttp will perform best when simple OkHttpClient instance is been created and reused it in program when every needed to make HTTP Calls, This is best each client is given to hold its own connection so this makes the task smooth, fast and easy to load data from server side.
Complete Source Code to make Http Request using OkHttp android library – Part 1
Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna use the HTTP flutter library to Fetch data from the Internet which is in JSON format, and display the data in Flutter ListView builder with ListTile widget.
void getData() async {
http.Response response = await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json"));
//if response is 200 : success that store
if (response.statusCode == 200) {
String data = response.body; //store response as string
setState(() {
superheros_length = jsonDecode(data)['superheros']; //get all the data from json superheros
print(superheros_length.length); // just printed length of data
});
var venam = jsonDecode(data)['superheros'][4]['power']; // get data from particular index
print(venam);
} else {
print(response.statusCode);
}
}
How to Show/Display data from Server in Flutter listView?
ListView.builder is commonly been used to construct a children’s widgets as much as required depending on the dynamic data you receive from server or API calls.
ListView.builder comes with parameters like
itemCount : describes how many itemBuilder ( widget ) must be created
Step 4 : Specifying the Google API key in AndroidManifest.xml ( ANDROID )
open AndroidManifest.xml file and add the <meta-data> tag inside <application> tag
<manifest ...
<application>
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR KEY HERE"/> // add this line and replace with you API KEY
</application>
</manifest>
Step 5: Specifying API key in AppDelegate.swift ( for iOS)
in iOS you need to Specify Application delegates to make use of google maps services in IOS
To do so navigate ios/Runner/AppDelegate.swift
import UIKit
import Flutter
import GoogleMaps // add this line
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("YOUR KEY HERE") // add this line replace with your API KEY
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
mapType: Specify which kind of map interface do you want to load.
normal.
satellite.
hybrid.
terrain.
initialCameraPosition: This will load the map with initial camera position may be currect location of the users.
onMapCreated: this will create a map with complete controls to the map you can zoom in, zoom out, go to other location in the map and many things under your controls.