Home Blog Page 33

Flutter Get Screen Tap Position X & Y Coordinates

0
Flutter Get Tap Position X & Y Coordinates

Hi Guy’s Welcome to Proto Coders Point, In this Flutter tutorial let’s learn how to get tap position i.e. X & Y axis coordinates when user taps on mobile screen.

This article is a quick guide on how to get user tap position XY coordinates in flutter.

Video Tutorial

How to get touch position of user

Flutter Tap Position X & Y Coordinates

In flutter, It’s very easily to get screen tap position by using GestureDetector Widget with onTapUp or OnTapDown event function.

Example:

GestureDetector(
      onTapDown: (position){
         final tapPosition = position.globalPosition;
         final x = tapPosition.dx;
         final y = tapPosition.dy;
         // do something with x & y
      },
      child: Scaffold(/* ..Whole App UI Screen.. */)
)

Flutter GestureDetector get position XY axis coordinates

Example:

flutter gesturedetector get tapped position x y axis coordinates

Source Code for Reference:

import 'package:flutter/material.dart';

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

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

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Offset? _tapPosition;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (position){
        setState(() {
          _tapPosition = position.globalPosition;
        });
      },
      child: Scaffold(
        appBar: AppBar(title: Text('ProtoCodersPoint.com'),centerTitle: true,),
        body: Center(
          child: Container(
            color: Colors.lightBlue,
            width: 300,
            height: 300,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('Tapped Position',style: TextStyle(color: Colors.white,fontSize: 30),),
                SizedBox(height: 12,),
                Text('X: ${_tapPosition?.dx.toString() ?? 'Tap SomeWhere'}',style: TextStyle(color: Colors.white,fontSize: 23),),
                SizedBox(height: 12,),
                Text('Y: ${_tapPosition?.dy.toString()?? 'Tap SomeWhere'}',style: TextStyle(color: Colors.white,fontSize: 23),)
              ],
            ),
          ),
        )
      ),
    );
  }
}

Recommended Flutter Article

Flutter Show Popup menu at long press position

How to make Flutter Button to acquire full width

0
Flutter Button Acquire Full Width Make Button Responsive

Hi Guys, Welcome to Proto Coders Point. This Article is on different ways to create a full width button in flutter, Basically How to make button acquire available screen width and make button responsive in flutter.

Video Tutorial

1. Elevated Button Full width – using Container / SizedBox

For any button to acquire complete available space (width), you need to wrap button widget i.e. (ElevatedButton, TextButton, OutlineButton) with Container widget / SizedBox the use width property with double.infinity so that it child will acquire the complete width of screen & make the button responsive in flutter.

Code Example:-

flutter button full width
Scaffold(
      appBar: AppBar(title: const Text('ProtoCodersPoint.com'),centerTitle: true,),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
        child: Column(
          children: [
            // Full width button Example 1
            SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                    onPressed: () {}, child: const Text('Elevated Button'))),
            const SizedBox(
              height: 20,
            ),
            // Full width button Example 2
            Container(
              width: double.infinity,
              color: Colors.transparent,
              child: OutlinedButton.icon(
                  onPressed: () {},
                  icon: const Icon(Icons.add),
                  label: const Text('Outlined Button')),
            ),
            const SizedBox(
              height: 20,
            ),
            // Full width button 3
            SizedBox(
              width: double.infinity,
              child: TextButton.icon(
                  onPressed: () {},
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('Text Button')),
            ),
          ],
        ),
      ),
    );

2.ConstrainedBox to give Full Width to Button widget

The another way to give full width to button widget is to wrap Elevated Button or any other button with ConstrainedBox & use it’s constraints property with BoxConstraints & set minWidth to double.infinity.

Code:-

constrainedBox minWidth
Scaffold(
      appBar: AppBar(title: const Text('ProtoCodersPoint.com'),centerTitle: true,),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
        child: Center(
          child: ConstrainedBox(
              constraints: const BoxConstraints(
                  minWidth: double.infinity, minHeight: 65),
              child: ElevatedButton(
                onPressed: () {},
                child: const Text('Elevated Button'),
              )),
        ),
      ),
    );

3. Material Button Full Width Flutter

In Flutter material button, We can make it responsive & acquire full width by setting material button property minWidth to double.infinity.

Code:-

flutter material button full width
Scaffold(
      appBar: AppBar(title: const Text('ProtoCodersPoint.com'),centerTitle: true,),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
        child: Column(
          children: [
            MaterialButton(
                shape: RoundedRectangleBorder (
                    borderRadius: BorderRadius.circular(20.0),
                    side: BorderSide(
                        width: 2,
                        color: Colors.blue
                    )
                ),
                minWidth: double.infinity,
                height: 60,
                color: Colors.orange,
                textColor: Colors.white,
                onPressed: () {},
                child: const Text('Material Button')),
          ],
        ),
      ),
    );

4. Elevated Button / TextButton set minimumSize

In ElevatedButton or any other button in flutter like (TextButton / OutlineButton), if you use style property with styleForm & set minimumSize parameter to Size.fromHeight (value), Here value is button height, then the button will acquire full width match to it’s parent.

Code:-

flutter elevated button acquire full width
 Scaffold(
      appBar: AppBar(title: const Text('ProtoCodersPoint.com'),centerTitle: true,),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
        child: Column(
          children: [
            ElevatedButton(
                style: ElevatedButton.styleFrom(
                  // The width will be 100% of the parent widget
                  // The height will be 60
                    minimumSize: const Size.fromHeight(60),
                  backgroundColor: Colors.purple,),
                onPressed: () {},
                child: const Text('Elevated Button')),
            const SizedBox(height: 20),
            OutlinedButton.icon(
                style: OutlinedButton.styleFrom(
                  // the height is 50, the width is full
                    minimumSize: const Size.fromHeight(50),
                ),
                onPressed: () {},
                icon: const Icon(Icons.run_circle),
                label: const Text('Outlined Button')),
          ],
        ),
      ),
    );

Flutter convert image to base64 string / base64 to image

0
onvert image to base64 or base64 to image in flutter

Hi Guy’s Welcome to Proto Coders Point. In this flutter article let’s learn how to convert image to base64 string or viceversa i.e converting base64 to image.

In flutter to encode Image into base64 string will make use of base64Encode & to decode base64 into image will use base64Decode method from dart:convert package, so import it.

import 'dart:convert'; 

Example 1 – Convert URL image into base64 in flutter

In below example, We have made use of http package to make internet call and get image from the image url & then encode it into base64.

Code:

void _getImageBase64() async{

     http.Response response = await http.get(Uri.parse('https://protocoderspoint.com/wp-content/uploads/2022/09/Whats-New-in-Flutter-3.3-696x392.jpg'));
     
     var _base64 = base64Encode(response.bodyBytes);

     print(_base64);
     
  }

Example 2 – Convert base64 string in image & show in Image Widget

To convert base64 to image, we make use of base64Decode method from dart:convert package.

As you seen in Example 1, We have Encoded image to base64 & stored the base64 string into a variable. Now let’s use the same base 64 string & convert/decode it back to image & display it in Image widget.

var _decodedImage = base64Decode(_base64);

// Now in Image.memory( ) Widget pass it.

Image.memory(_decodedImage);

Example 3: Pick Image for gallery & convert it to base64 string

In flutter app to pick image from gallery will make use of image_picker package, that helps use in picking images from gallery or capture image for camera.

I have wrote a complete article on image picker in flutter with example to learn more check it now.

Below source code in an example on How to pick image from gallery & convert the picked image file into base64 string.

read the comment in source code for understanding.

class _MyHomePageState extends State<MyHomePage> {

  File? _imageFile;  // picked image will be store here.
  final ImagePicker _picker = ImagePicker(); //instance of image_picker

   // a function to pick image and convert it into base64 string

  void _pickImageBase64() async{
    try {
       // pick image from gallery, change ImageSource.camera if you want to capture image from camera.
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;  
       // read picked image byte data.
      Uint8List imagebytes = await image!.readAsBytes();

      // using base64 encoder convert image into base64 string.
      String _base64String = base64.encode(imagebytes);

      print(_base64String);
      
      final imageTemp = File(image.path);
      setState(() {
        this._imageFile = imageTemp;   // setState to image the UI and show picked image on screen.
      });
    }on PlatformException catch (e){
      if (kDebugMode) {
        print('error');
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
           children: [
             _imageFile == null ? Container() : Image.file(_imageFile!,width: 250,height: 500,),  // show picked image here
             ElevatedButton(onPressed: (){
                  _pickImageBase64();
             }, child: Text("Pick Image Convert to base64")),

           ],
        ),
      ),
    );
  }
}

Quick Revision OOPS concepts of java – asked in interview

0
java oops concept quick revision

Hi Guy’s Welcome to Proto Coders Point. This Article is on basic quick revision oops concepts of java that can be asked in interview.

Object Oriented Programming System(OOPs)

If we take real world example, a Object are pen, table, personal computer… etc. In JAVA Programming OOPs is a methodology used to design programs using classes & objects. By using object oriented we can make software development simple. Here are the OOPS Concepts:

Quickly Revise OOPS Concepts

  1. Object.
  2. Class.
  3. Inheritance.
  4. Encapsulation.
  5. Abstraction.
  6. Polymorphism.
java oops concepts quick revision

Here inheritance, encapsulation, abstraction, & polymorphism are called as four pillars of JAVA Programming language.

1. Object

Any real world entity is an Object. It has Behavior and Attribute. Here:

Behavior can be defined as what an object does and what is can perform.

Attribute is used to describe a Object.

Here is a small example:

Chair: In Real word a chair is an object, which has behaviour feature like wheem movement, Height and recline adjectment. and chair’s attribute like it’s color, number of wheels, max height adjuctment, price etc.


2. Class

The collection of all related object is called as class, Consider general category as a class, which contains related objects within it.

Example: Chair

Object like Office Chair, Wheel chair, recliner chair, gaming chai etc all this below to one class that is Chair class.


3. Inheritance

To Understand Inheritance concept in java, let’s take real world eg: In child aquire the qualities from his/her parent. Similarly, a Child class can also inherit feature from it’s parent class.

Basically Inheritance is a machanism by which one class (child) can aquire all the properties/features of another class(parent).

Example: Phone

Parent class Phone can have two child classes -:

  • TelePhone
  • MobilePhone

Both of this child classes has inherited a calling feature behaviour.


4. Encapsulation

In Java Encapsulation means wrapping up of data into a single unit & securing it, By encapsulation process data will get secured from outside words.

Example:

Bank Locker: You create a bank locker where you keep all your valuable thinks lets say the locker as (single unit) and then you protect the locker using a key or digital passcode.

Medicine Capsules: It has a wraps from outside and all the medicine ingredient is wraps into that capsules for protecting it from outsite atmosphere.


5. Abstraction

The Inside working machanism is been hidden from the user, and the user can only be able to user those feature, which him/her know how the machanism actual works.

This helps the user to be focus on product usage.

Eg:

Car: A Car, is full of complexity machanism like engine, gear box. User no need to know in depth about this. Only the relevent part is shown like brakes, accelerator, gear’s how to use it.


6. Polymorphism

The word polymorphism means many forms, The meaning of polymorphism means same name can we used for different behavious.

Eg: Chess: All chess pieces like king, bishop, knight, rook … etc move in different directions, Bishop moves diagnallym Rooks move horizontal and verticle etc.

The common behaviour in chess game is “move”, but the different over here is direction.


Conclusion

This article is basic revise of Java OOPS Concepts, We can use OOP Concepts to map any real-world solutions into programming very easily.

That’s why OOP concept is designed close to real world.

A Better understanding of these concepts is going to decide how good programmers we will become in future. Have a look at Dart programming OOPS Concepts

Upload CSV file into Azure SQL Database – Import csv to sql server

0
Import csv to Azure SQL Database

Hi Guy’s Welcome to Proto Coders Point, In this Tutorials we will learn about the Microsoft Azure Database and How to import data from csv file to sql database

Requirements: –

  1. IDE or Notebook
  2. Database Credential
  3. JDBC Connection

1) IDE or Notebook

          It is web interface that contain runnable commands, visualizations, We create notebook using some default languages i.e. Python, SQL, Scala, R, Pyspark.

2) Database Credentials: –

          We need to make sure that all Database Credentials are required to connect with the Database i.e. Server Name, Database Name, ID, Password.

 3) JDBC Connection: –

          Connection is used to load the driver and help to establish connect with the Data Source.

4) CSV FILE:-

Comma-Separated Value is a text file which data is available in spreadsheet format.


Creating SQL Database on Azure Cloud

First of all, We Need to Create a SQL Database on Azure. We have shared some step that help you to create SQL Database.

  • Go to Search Tab in Azure.
  • Search for ‘SQL Database’ & click on It.
  • Click on ‘Create’.
    • Add project Details
      • Subscription
      • Resource Group
    • Database Details
      • Database Name (Add Database Name)
      • Server Name (Choose Same Region that are already defined in SQL Server)
      • Workload Environment – Choose development OR Production Environment
      • Compute + Storage –
  • Backup Storage Redundancy
    • Choose Locally OR Geo Storage Redundancy

Connect databricks to sql server using python code

After creating a Database in Azure we will try to connect to Database Using Data bricks: –

While accessing a Database azure we have certain ways to connect like CLI, Programming, SQL Server Management Studio.

We are going to use Python Programming for accessing Database with JDBC Connection (databricks connect to sql server python).

Step 1:- First will connect with the SQL Database by using JDBC Port:

from pyspark.sql import *
import pandas as pd

jdbchost_name = "firstserver31.database.windows.net" //Server Name 
jdbcPort = "1433"
jdbcDatabase = "task1" //Database Name
properties = {
    "user" : " ",
    "password" : " "
}
url = "jdbc:sqlserver://{0}:{1};database={2}".format(jdbchost_name, jdbcPort, jdbcDatabase)

Step 2:- After connecting with the Database we will read a CSV file

file_df = sqlContext.read.csv("/FileStore/tables/emp/employees.csv", header = True)
file_df.show(5)

Step 3:- Write CSV File into the Database.

filedf1 = DataFrameWriter(file_df)
filedf1.jdbc(url=url, table="employee1", mode="overwrite", properties=properties)
print("Successfully added Into Database")

#Output :-

imported csv to sql using python

In Next Tutorial we will come with the Simple ETL Process by Using the Same Technologies.

How to create Reorderable Listview in flutter

0
Flutter reorderable list view with example
Flutter reorderable list view with example

Hi Guy’s Welcome to Proto Coders Point. In this Flutter tutorial let’s learn how to implement Reorderable listview in flutter app.

What is Reorderable Listview in flutter

Basically a reorderable listview looks similar to listview, the only difference over here is that the user can interact with listview by long press on list item drag & drop to reorder the listview item as per user needs.

Example: Can be used this in developing a simple ToDo application in flutter where a user can reorder his todo list and keep priority task on top.

Video Tutorial

Flutter ReorderableListView Widget & it’s Syntax

In flutter we have a widget i.e. ReorderableListview, It has 2 main properties to be passed (children & onReorder).
and alternatively we have ReorderableListView.builder, It has 3 mandatory properties (itemBuilder, ItemCount, OnReorder). Example below.

Syntax of ReorderableListview

ReorderableListView(
        children: [
              // listview items
        ],
        onReorder: (int oldIndex, int newIndex){
              // list items reordering logic
        },
      )

Syntax of ReorderableListView.builder(….)

ReorderableListView.builder(
          itemBuilder: itemBuilder,    // widget to show in listview Eg: ListTile
          itemCount: itemCount, // number of item to generate in listview
        onReorder: (int oldIndex, int newIndex){
          // list items reordering logic
        },
  )

Reorderable ListView in Flutter – Complete Source Code

Initialize Dummy List by using list generator

 final List<int> _itemList = List<int>.generate(60, (index) => index);

Example 1 – With Video Tutorial

ReorderableListView(
        onReorder: (int oldIndex, int newIndex) {
          setState(() {
            if(newIndex > oldIndex){
              newIndex -=1;
            }
            final int temp = _itemList[oldIndex];
            _itemList.removeAt(oldIndex);
            _itemList.insert(newIndex, temp);
          });
        },
        children: [
          for(int index = 0;index<_itemList.length;index++)
            ListTile(
              key:Key('$index'),
              title: Text('Item ${_itemList[index]}'),
            )
        ],
   ),

Example 2 – With Video Tutorial

ReorderableListView.builder(
          itemBuilder: (BuildContext context,int index){
            return Card(
              key: Key('${index}'),
              child: ListTile(

                title: Text('Item ${_itemList[index]}'),
              ),
            );
          },
          itemCount: _itemList.length,
          onReorder: (int oldIndex,int newIndex){
              setState(() {
                if(newIndex > oldIndex){
                  newIndex -=1;
                }
                final int tmp = _itemList[oldIndex];
                _itemList.removeAt(oldIndex);
                _itemList.insert(newIndex, tmp);
              });
      })

Example 3 – Make API Http call request & create a Reorderable Listview – Complete Code

Demo

reorderable listview flutter
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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> {
  
  var jsonList;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  void getData() async{

    http.Response response = await http.get(Uri.parse("https://protocoderspoint.com/jsondata/superheros.json"));
    if(response.statusCode == 200){
       setState(() {
           var newData = json.decode(response.body);
           jsonList = newData['superheros'] as List;
       });
    }else{
      print(response.statusCode);
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Reorderable Listview"),
      ),
      body: ReorderableListView.builder(
          itemBuilder: (BuildContext context,int index){
            return Card(
              key: Key('${index}'),
              child: ListTile(
                leading: ClipRRect(
                  borderRadius: BorderRadius.circular(80),
                    child: Image.network(
                        jsonList[index]['url'],
                      fit: BoxFit.fill,
                      width: 50,
                      height: 100,
                    )
                ),
                title: Text(jsonList[index]['name']),
                subtitle: Text(jsonList[index]['power'],maxLines: 4,),
              ),
            );
          },
          itemCount: jsonList == null ? 0 : jsonList.length,
          onReorder: (int oldIndex,int newIndex){
            setState(() {
              if(newIndex > oldIndex){
                newIndex -=1;
              }
              final tmp = jsonList[oldIndex];
              jsonList.removeAt(oldIndex);
              jsonList.insert(newIndex, tmp);
            });
          })
    );
  }
}