Home Blog Page 61

Flutter Rating dialog – Redirect user to app page PlayStore/AppStore

0
how to open playstore from flutter app
how to open playstore from flutter app

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, We will create a Rating dialop popup box with star rating UI & then re-direct users to app page in Google PlayStore or apply AppStore for review rating purpose.

To achieve this we are going to make use of 2 flutter packages.

Video Tutorial


1. Rating_Dialog:

This Library is used to add a beautiful & customizable rating dialog in flutter.

This Package will help us in showing a rating dialog pop, whee we can ask users to share their experience review about app (Rate My App) & then redirect user to app page on Google PlayStore / Apple App Store for review & rating purpose.

I have wrote a complete seperate tutorial on rating_dialog, please check it here.

Add Rating Dialog dependencies in flutter project

Open pubspec.yaml file and under dependencies add it

dependencies:
  flutter:
    sdk: flutter
  rating_dialog: ^2.0.1              #add this line

Import rating_dialog.dart

now you need to just import the library where you want to show dialog rating.

import 'package:rating_dialog/rating_dialog.dart';

Create an Instance of RatingDialog Widget

  final _dialog = RatingDialog(
    // your app's name?
    title: 'Rate Us On App Store',
    // encourage your user to leave a high rating?
    message:
    'Select Number of Stars 1 - 5 to Rate This App',
    // your app's logo?
    image: const FlutterLogo(size: 60),
    submitButton: 'Submit',
    onCancelled: () => print('cancelled'),
    onSubmitted: (response) {
      print('rating: ${response.rating}, comment: ${response.comment}');

      // TODO: add your own logic
      if (response.rating < 3.0) {
        // send their comments to your email or anywhere you wish
        // ask the user to contact you instead of leaving a bad review
      } else {
        //go to app store
        
      }
    },
  );

Then to show the dialog box we make use of flutter showDialog function with will invoke above dialog widget.

showDialog(
              context: context,
              builder: (context) => _dialog,
      );

2. Store_redirect:

By using this library we can redirect users from your app to app page i.e. Google PlayStore or Apple AppStore.

Add Store Redirect dependencies in flutter project

dependencies:
  flutter:
    sdk: flutter
  rating_dialog: ^2.0.1
  store_redirect:                       #add this line

Import store_redirect.dart

now you need to just import the library where you want to use store redirect.

import 'package:store_redirect/store_redirect.dart';

OnButton click natigate user to playstore or appstore

 StoreRedirect.redirect(androidAppId: 'shri.complete.fitness.gymtrainingapp',iOSAppId: 'com.example.rating');

In above StoreRedirect.redirect, we need to pass 2 parameter i.e. your AppId

  • androidAppID: your android AppID.
  • iOSAppId: your iOS AppId.

This Library will automatically control where the user should be redirected, Suppose if user is Android User then he will be navigated to playstore and if the user is iOS User then he will be navigated to Apply AppStore.


Complete Code : Flutter Rating Dialog – Redirect user to playstore/appstore

main.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:rating_dialog/rating_dialog.dart';
import 'package:store_redirect/store_redirect.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(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final _dialog = RatingDialog(
    // your app's name?
    title: 'Rate Us On App Store',
    // encourage your user to leave a high rating?
    message:
    'Select Number of Stars 1 - 5 to Rate This App',
    // your app's logo?
    image: const FlutterLogo(size: 60),
    submitButton: 'Submit',
    onCancelled: () => print('cancelled'),
    onSubmitted: (response) {
      print('rating: ${response.rating}, comment: ${response.comment}');

      // TODO: add your own logic
      if (response.rating < 3.0) {
        // send their comments to your email or anywhere you wish
        // ask the user to contact you instead of leaving a bad review
      } else {
        //go to app store
        StoreRedirect.redirect(androidAppId: 'shri.complete.fitness.gymtrainingapp',iOSAppId: 'com.example.rating');
      }
    },
  );


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: (){
            
             // load dialog to show it 
            showDialog(
              context: context,
              builder: (context) => _dialog,
            );
          },child: Text('Show Rating Dialog'),
        ),
      )
    );
  }
}

Flutter web implementing drop down with hover effect

0
Flutter Web hover effect in dropdown list
Flutter Web hover effect in dropdown list

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will learn how to implement flutter dropdown with hover effect animation.

Note: Hovering effect in flutter works only on flutter web & By running same code in android & iOS you will not see any hovering animation effect.

Below GIF image is the final output for this tutorial, we have a app which has a flutter dropdown with hover effect, when a mouse pointer is hovered on items of dropdown list, you can see a item is highlighted with a slight animation effect.

Now let’s create this from start…..

1. Create/Open a flutter project

Firstly, create/open any new flutter project where you want to implement hover effect on dropdown list, I make use of Android Studio with is best IDE for Flutter development.

File -> New -> New Flutter Project(finish) // project is ready.


2. Create a custom flutterWidget OnHover.dart

Under lib directory, create a new dart file & name it as OnHover.dart.

So OnHover.dart will be our custom stateful widget which has properties such as animatedContainer & MouseRegion widget which is use to detect when our mouse pointer comes in MouseRegion to perform hover effect in flutter with animation to any widgets.

OnHover.dart

import 'package:flutter/material.dart';

class OnHover extends StatefulWidget {

  final Widget Function(bool isHovered) builder;

  const OnHover({Key? key, required this.builder}) : super(key: key);

  @override
  _OnHoverState createState() => _OnHoverState();
}

class _OnHoverState extends State<OnHover> {

  bool isHovered = false;
  @override
  Widget build(BuildContext context) {

     // on hover animation movement matrix translation
    final hovered = Matrix4.identity()..translate(10,0,0);
    final transform = isHovered ? hovered : Matrix4.identity();

    // when user enter the mouse pointer onEnter method will work
   // when user exit the mouse pointer from MouseRegion onExit method will work
    return MouseRegion(
      onEnter: (_)=> onEntered(true),
      onExit: (_)=> onEntered(false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        transform: transform,             // animation transformation hovered.
        child: widget.builder(isHovered),   // build the widget passed from main.dart
      ),
    );
  }

  //used to set bool isHovered to true/false
  void onEntered(bool isHovered){
    setState(() {
      this.isHovered = isHovered;
    });
  }
}

OnHover custom widget can be used to give hover effect to any widget in flutter, you just need to wrap widget with OnHover widget builder.


3. Create a dropdown list in flutter with hover effect

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hover_eg/OnHover.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(
        primarySwatch: Colors.blue,
      ),
      home: DropDownPage(),
    );
  }
}


class DropDownPage extends StatefulWidget {
  const DropDownPage({Key? key}) : super(key: key);

  @override
  _DropDownPageState createState() => _DropDownPageState();
}

class _DropDownPageState extends State<DropDownPage> {
  //list of item to show in flutter drop down 
  static final data = ['Lion', 'Tiger', 'Shark', 'Snake', 'Bear','Crocodile','Monkey'];
  String initial = data.first.toString();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
          child: DropdownButton(
            value: initial,
            icon: Icon(Icons.keyboard_arrow_down),
            items: Textpage.texts.map((String items) {
              return DropdownMenuItem(
                  value: items,
                  child: OnHover(
                     //Wraping the DropDownMenuItem child so then when Items of drop down is hovering we see hovering effect
                    builder: (isHovered){
                      final color = isHovered ? Colors.blue:Colors.black;
                      return Text('$items',style: TextStyle(color: color),);
                    },
                  ));
            }).toList(),
            onChanged: (String? newvalue){
              setState(() {
                initial = newvalue!;
              });
            },
          )
      ),
    );
  }
}

Hover effect in flutter web – hover effect with animation to any widget

0
hover effect in flutter web
hover effect in flutter web

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will learn how to give hover effect in flutter web.

Note: Hover effect in flutter can only be implemented on flutter web app, therefore onhover in mobile device will not give any hovering effect.

Video Tutorial

flutter hover effect video tutorial

so let’s begin with the coding.

How to give hover effect to any widget in flutter

1. Create a flutter project

Open you favorite IDE & create/open a new flutter project, I am using android-studio to build flutter projects.

File > New > New Flutter Project ( Give a good name to flutter project & finish) your project will get created.

2. Create a dart file OnHover.dart

Under lib directory, create a new dart file & name it as OnHover.dart.

So OnHover.dart will be our custom stateful widget which has properties such as animatedContainer & MouseRegion widget which is use to detect when our mouse pointer comes in MouseRegion to perform hover effect in flutter with animation to any widgets.

OnHover.dart

import 'package:flutter/material.dart';

class OnHover extends StatefulWidget {

  final Widget Function(bool isHovered) builder;

  const OnHover({Key? key, required this.builder}) : super(key: key);

  @override
  _OnHoverState createState() => _OnHoverState();
}

class _OnHoverState extends State<OnHover> {

  bool isHovered = false;
  @override
  Widget build(BuildContext context) {

    final hovered = Matrix4.identity()..translate(0,-10,0);
    final transform = isHovered ? hovered : Matrix4.identity();

    return MouseRegion(
      onEnter: (_)=> onEntered(true),
      onExit: (_)=> onEntered(false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        transform: transform,
        child: widget.builder(isHovered),
      ),
    );
  }

  void onEntered(bool isHovered){
    setState(() {
      this.isHovered = isHovered;
    });
  }
}

3. Add Hover effect to any widget in flutter

Now, our OnHover custom widget is ready(above), so now we can use it to give animation & hover effect to any widget in flutter.

To do that you need to simply wrap any widget with OnHover widget builder to apply Hovering effect.

Examples:

Flutter text animation on hover – change text color

OnHover(builder: (isHovered){
              return Text("Flutter Text on hover - change text color on hovering with animation");
 }),

Change Container Color on Hover

 OnHover(builder: (isHovered){
              final color = isHovered ? Colors.grey : Colors.blue;
              return
                Container(
                  color: color,
                  width: 100,
                  height: 100,
                );

            }),
flutter change container color on hover

Hover elevation flutter

OnHover(builder: (isHovered){
              return
              PhysicalModel(
                color: Colors.blue,
                elevation: isHovered ? 16 : 0,      // if ishovered true then show elevation on hovering
                child: Container(
                  width: 100,
                  height: 100,
                ),
              );

       }),
flutter elevation hover effect

change flutter button color on hover

OnHover(builder: (isHovered){
              final  color = isHovered ? Colors.red : Colors.blue;
              return
               ElevatedButton(
                   style: ElevatedButton.styleFrom(primary: color),
                   onPressed: (){}, child: Text('Change Button Color on hover')
               );

            }),
flutter button color change on hover


main.dart complete code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hover_eg/OnHover.dart';
import 'package:flutter_hover_eg/text_page.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(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hover Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            OnHover(
              builder: (isHovered) {
                final color = isHovered ? Colors.orange : Colors.redAccent;
                return PhysicalModel(
                  color: Colors.white,
                  elevation: isHovered ? 16 : 0,
                  child: Container(
                      height: 50,
                      width: 200,
                      color: color,
                      child: Center(
                        child: Text("Proto Coders Point"),
                      )),
                );
              },
            ),
            SizedBox(
              height: 30,
            ),
            OnHover(builder: (isHovered) {
              return Text(
                  "Flutter Text on hover - change text color on hovering with animation");
            }),
            SizedBox(
              height: 30,
            ),
            //if isHovered is true then show elevation else set elevation to 0
            OnHover(builder: (isHovered) {
              return PhysicalModel(
                color: Colors.blue,
                elevation: isHovered ? 16 : 0,
                child: Container(
                  width: 100,
                  height: 100,
                ),
              );
            }),

            OnHover(builder: (isHovered) {
              final color = isHovered ? Colors.grey : Colors.blue;
              return Container(
                color: color,
                width: 100,
                height: 100,
              );
            }),
            SizedBox(
              height: 30,
            ),
            OnHover(builder: (isHovered) {
              final color = isHovered ? Colors.red : Colors.blue;
              return ElevatedButton(
                  style: ElevatedButton.styleFrom(primary: color),
                  onPressed: () {},
                  child: Text('Change Button Color on hover'));
            }),
          ],
        ),
      ),
    );
  }
}

Prime Number program in dart

0
CHECK PRIME NUMBER Dart Program
CHECK PRIME NUMBER Dart Program

Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn, What is a prime number, check if a given number in prime or not & a dart program to print prime number from 1 to N.

What is a Prime Number?

A Prime Number in math are the numbers that are greater then 1 & are divisible by 1 or itself.

In other Words, A number that can’t be divided by any other number, rather then 1 or itself.

Prime Number Examples

Eg:

5 => 5 can’t be divided by any other numbers.
3 => 3 can’t be divided by any other numbers.
7 => 7 can’t be divided by any other numbers.
13 => 13 can’t be divided by any other numbers.

Not a Prime Number Examples

Eg:

4 => 4 is divisible by 2 so it not a prime number.
6 => 6 is divisible by 2 so it not a prime number.
8 => 8 is divisible by 2 so it not a prime number.
10 => 10 is divisible by 2 so it not a prime number.

If you observe you can see that, all the even number are not a prime number, except 2.

NOTE: 0 and 1 are always said to be not a prime number.

How to check if a number is prime or not in dart

Let’s write dart programs to check if a number is prime or no.

1. Dart Program to check a number prime or no

In this dart program, we will initialize a Integer with a number value & then check if that number is prime or no.

void main(){
  int i,m=0,flag=0;
  int num = 5;

  m=num~/2;

  for(i = 2;i<=m;i++){
    if(num%i == 0){
      print('$num is not a prime number');
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num is prime number');
  }
}

2. check prime number using method in dart program

void main(){
     // call method by passing a integer value to it
     checkPrime(5);
     checkPrime(8);
     checkPrime(13);
     checkPrime(76);
     checkPrime(7);
}

// a method that checks prime or not prime
void checkPrime(int num){
   int i,m=0,flag=0;
 
  m=num~/2;


  for(i = 2;i<=m;i++){
    if(num%i == 0){
      print('$num is not a prime number');
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num is prime number');
  }
}
dart program check prime number

3. Prime number dart program – take input from user

So now in below code, the number to be checked is not predefined, Here the dart code will ask the user to enter a number to be checked whether it a prime or not

import 'dart:io';
import 'dart:math';
void main(){
  

   print('Enter number to check prime or no');

   int? num = int.parse(stdin.readLineSync()!); 

  print('$num');

  if(CheckPrime(num)){
           print('$num is a prime');
  }else{
    print('$num is not a prime');
  }

}

bool CheckPrime(int num){

  if(num<=1){
     return false;
  }
  
  for (int i = 2;i<=sqrt(num);i++){
    if(num%i == 0){
      return false;
    }
  }
  return true;

}
prime number program in dart
prime number program in dart

4. Dart program to print prime number from 1 to N

Now let’s write a dart program to print all the prime numbers from 1 to N.

import 'dart:io';
import 'dart:math';

void main(){
      print('Enter Nth');
      int? N = int.parse(stdin.readLineSync()!);
      print('----------------------------');
      for(int i=2;i<= N;i++){
        checkPrime(i);
      }
}

void checkPrime(int num){
   int i,m=0,flag=0;
   m=num~/2;
  for(i = 2;i<=m;i++){
    if(num%i == 0){
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num');
  }
}
print prime number 1 to N


Similar dart programs to learn dart language

Generate Random number in dart

palindrome program in dart

ArmStrong number program in dart

Fibonacci sequence in dart

pattern program in dart

string to ascii

prime number program in dart

How to dismiss keyboard in flutter – lose textfield focus

0
how to dismiss keyboard in flutter
how to dismiss keyboard in flutter

Hi Guys, Welcome to Proto Coders Point. OK so your are looking for a solution that, when a user tap outside TextField you need to dismiss the keyboard from the screen and want to textfield lose focus.

So In this Flutter Tutorial, let’s Learn how to dismiss the keyboard in flutter when user tap on the screen.

Two Examples how to dismiss a keyboard

  1. Example 1: When user tap on any Empty space on the Mobile screen, The keyboard should get dismissed and the textfield which is focused should also get unfocused.
  2. Example 2: Suppose you have a Listview with lists of widget(Text Input Field) in it, then user fill the textfield and scroll down, than the keyboard should get dismissed and flutter textfield lose focus on listview scroll.

Example 1 – To dismiss the keyboard and lose focus

Step 1: Wrap Scaffold with GestureDetector

You must implement a tap detector (GestureDetector onTap), when user tapped outside the current active textField.

GestureDetector(
  onTap: () {},
  child: ...//Eg: Scafford
)

You can Simply achieve this by using GestureDetector widget, which makes it simple and easiest way to detect onTap outside the focused TextField.

Step 2: On Tap Dismiss the keyboard

To close keyboard / to hide the keyboard you need to simply remove focus from textfield & thus it automatically dismiss the keyboard.

So to remove focus from textfield you just need to run FocusScope unfocus, when user tap outside the textfield.

FocusScope.of(context).unfocus();
Snippet code

GestureDetector(
      onTap: ()=> FocusScope.of(context).unfocus(), // on tap run this code
      child: ...// Scaffold Widget
    );

Complete Code for Example 1 to dismiss keyboard in flutter

import 'package:flutter/material.dart';

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ()=> FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(title: Text('KeyBoard Example'),),
        body: Padding(
           padding: const EdgeInsets.all(16.0),
           child:TextField(
           decoration: InputDecoration(
             border: OutlineInputBorder(),
             labelText: 'Enter your Name'
           ),
         ),
        ),
      ),
    );
  }
}


Example 2 – On ListView Scroll dismiss keyboard

Suppose you have a Listview with lists of widget(Text Input Field) in it, then user fill the textfield and scroll down, than the keyboard should get dismissed and flutter textfield lose focus on listview scroll.

In that case you can make user of Listview keyboardDismissBehaviour with ScrollViewKeyboardDismissBehavior.onDrag

 ListView(
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        children: [
           // list of childs
        ],
      )

keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag: When a keyboard is active and user scroll through the listview then keyboard will get dismissed automatically

Check out the example in below gif image.

Complete Code to dismiss keyboard on scroll

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(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('KeyBoard Example'),),
      body: ListView(
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child:TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Enter your Name'
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child:TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Enter your Name'
              ),
            ),
          ),
          Text("Enter Some Text here",style: TextStyle(fontSize: 30),),
         // add more widgets here 
        ],
      )
    );
  }
}



How to create custom dialog box with floating image app logo in android

0
custom alert dialog in android
custom alert dialog in android

Hi Guys, Welcome to Proto Coders Point. In this Android tutorial, we will learn how to create a custom dialog box with a floating image app logo.

Sometimes a simple & default android dialop popup is not suitable with our app UI, In that case we need to create a custom alert dialog layout design to show as a popup to a user.

Example: Check the below image, this is what we will achieve at the end.
A android custom popup dialop example with a floating imageview sightly out of dialog as shown in below screenshot.

custom alert dialog in android design

Video Tutorial

Below are steps to achieve above android alert dialog.

Step 1: create a background for custom dialog layout

Create a XML file: dialog_bg.xml in drawable folder and copy paste the below code in it.

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"

    android:insetLeft="5dp"
    android:insetTop="5dp"
    android:insetBottom="5dp"
    android:insetRight="5dp"
    >

    <shape android:shape="rectangle">
        <corners android:radius="20dp"/>
        <solid android:color="@color/white"/>
        <stroke android:width="5dp" android:color="#FFF"/>
    </shape>

</inset>

The above code is just to give a corner radius, solid color, and stroke to custom_dialog.xml background.


Step 2: Create a vector image(cancel image) and copy a logo image in drawable

Create vector assets image
Right click on drawable -> New -> Vector Assets & choose a cancel button.

We need a logo image file to show in dialog popup as a floating app logo, So just copy your app logo in drawable file.

logo.png

Step 3: Creating a custom_dialog.xml layout file under layout folder

Now a main custom alert dialog layout design custom_dialog.xml, Under layout folder create a XML file custom_dialog.xml and copy below layout code and paste in it.

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

    <LinearLayout
        android:background="@drawable/dialog_bg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp">

        <ImageView
            android:id="@+id/cancel_button"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@drawable/ic_cancel"
            android:layout_centerHorizontal="true"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp"
            android:layout_gravity="right"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="WELCOME TO PROTO CODERS POINT"
                android:textColor="#000"
                android:textStyle="bold|italic"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Please do like and Subscribe Us"
                android:textColor="#000"
                android:textStyle="bold|italic"
                />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="OK"
                android:gravity="center"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"/>


        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/logo"
        />

</RelativeLayout>

This code defines different views inside a custom dialog layout, it has 2 imageview, one for App logo and another for cancel vector image and 2 TextView and a ‘OK’ button.


Step 4: activity_main.xml add a button

In activity_main.xml file will add a button, when a user clicks on that button will show android dialog.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Dialog"
        android:id="@+id/showdialog"
        />

</LinearLayout>

Step 5: MainActivity.xml on click show alert dialog in android

On Button click create a custom dialog in android and show it to the user.

MainActivity.java

package example.on.dialog_popup;


import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {

    Button showdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //find the view
        showdialog = (Button)findViewById(R.id.showdialog);

       // when clicked 
        showdialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 ImageView cancel;
                 //will create a view of our custom dialog layout
                 View alertCustomdialog = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_dialog,null);
                //initialize alert builder.
                AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                
                //set our custom alert dialog to tha alertdialog builder
                alert.setView(alertCustomdialog);
                cancel = (ImageView)alertCustomdialog.findViewById(R.id.cancel_button);

                final AlertDialog dialog = alert.create();

                //this line removed app bar from dialog and make it transperent and you see the image is like floating outside dialog box.
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

                //finally show the dialog box in android all
                dialog.show();

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });


            }
        });

    }
}


Recommended Android and Flutter Posts

Android Alert dialog Box with list of options in it.

Alert dialog box in flutter