Home Blog Page 62

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

Android emulator was killed – ERROR SOLUTION

0
Android emulator was killed
Android emulator was killed

Hi Guys, Welcome to Proto Coders Point.

So, I just tried starting AVD Android Emulator but what was actually happening is, when i start Emulator it was showing connecting to the emulator & suddenly it showed android emulator was killed.

Then, i tried some solution from stackoverflow and found a solution that worked for me. so just thought to share about this to you.

So here are some solution you need to try. The Solution 1 worked for me.

Solution 1: Check your drive free space( This worked for me)

I have a SSD drive, where my windows OS is installed & Android Studio is allso installed in SSD for fast loading with Emulator.

Android Studio Emulator consume atleast 8 GB of space in C: drive, Then if there is no space in C: drive & you try to start Android emulator then due to low storage, android emulater will kill itself.

Please check drive C:, it should have atleast 10 GB of free memory for emulator to run smoothly.


Solution 2: intel x86 Emulator Accelerator update

Check if you have installed ‘‘intel x86 Emulator Acceleration” SDK tools, if YES check if it updated else just install it and keep it up-to-date.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [intel x86 Emulator Accelerator(HAXM installer)] and update it.
android studio install intel x86 emulator accelerator

Solution 3: Install/Update Android Emulator SDK tools

There might be some issue if you are using lower version of SDK tools Android Emulator =, so kindly be updated with latest version of android Emulator.

Android-Studio > Tools > SDK Manager > SDK Tools(Tab) > tick [Android Emulator] and update it
android emulator sdk tools install

final and const keyword in dart – what’s difference

0
final and const keyword in dart
final and const in flutter dart

Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn what is the difference between final and const keyword in flutter dart.

Even dart programming language support assigning a constant value to a dart variable, Here constant value means once a value is assigned to the variable then it cannot be altered/changed.

There are 2 keywords used to declare constant variable in dart:

  1. const keyword.
  2. final keyword.

Const Keyword in dart

The const keyword in dart, are similar to final keyword but, The only different between const & final is, In const variable initialization can only be done during compile-time, means a variable value cannot be initialized at run-time.

Example: 
String name;

//get input to name from user
name = stdin.readLineSync();

//you will get error; doing this
const copyname = name; //error

In Simple words, by using const keyword you cannot take input from user and then assign to const variable in run-time. but by using const you can assign value directly at compile-time only.

Example:
const number = 85785;
// later this can't be changed; like this
number = 854; // cant do this


When to use const keyword

Suppose you have a value that will never alter or should not be changed during run-time. Eg: A String ‘ProtoCodersPoint’ will always be same for a app name, but if you are integrating a time in your app then const should not be used for currect time because it keep change every milli seconds.


final keyword in dart

In final keyword, the only different i we can assign a value to final variable at run-time(but only once), that means we can assign value to final keyword by taking manual input from user, but once value is been assigned then cannot be altered.

Example

final int? number;

number = int.parse(stdin.readLineSync());

Print(number);
//Now number is already assigned.
//then it can’t be altered again like this;

number = 100; // Error: Not Possible to change the value.


Example on final & const keyword

void main(){
     finalvariable(500);
     constvariable(5);
}

void finalvariable(int value){
  final finalvariable = value;
  print(finalvariable);

   //finalvariable = 5000; // this is not possible
}
void constvariable(int value){

  const directinit = 100;
  print(directinit);
 // const variableconst = value; // after compile time, initializing value to const variable is not possible

}