Home Blog Page 11

Flutter Cupertino Timer Picker example with source code

0
FLUTTER CUPERTINO TIMER PICKER
FLUTTER CUPERTINO TIMER PICKER

Cupertino Timer Picker is IOS style timer picker in flutter, that allows user to search a duration of time or a time interval. In this Flutter Article let’s learn how to implement CupertinoTimerPicker in flutter with complete source code.

If you’re looking for a Cupertino-style timer picker i.e ios style time picker, then flutter provide a Timer Picker widget in Material Design class named CupertinoTimerPicker Here’s a basic example of how you can create a Cupertino-style timer picker:

We can make use of showCupertinoModalPopup widget to show a popup from the bottom of the screen.

Video Tutorial

Creating the Timer Picker Widget:

We have a function _showTimerPicker that open a popup at the bottom of the screen and displays the Timer Picker when a user press on a button to select a time duration user can select time in hours, minutes and seconds, To show type of mode that i.e. hms we can make use of mode property from CupertinoTimerPicker widget.

snippet – CupertinoTimerPacker Widget constructor

CupertinoTimerPicker(
{
 Key? key,
 CupertinoTimerPickerMode mode = CupertinoTimerPickerMode.hms,
 Duration initialTimerDuration = Duration.zero,
 int minuteInterval = 1,
 int secondInterval = 1,
 AlignmentGeometry alignment = Alignment.center,
 Color? backgroundColor, 
 double itemExtent = _kItemExtent, 
 required ValueChanged<Duration> onTimerDurationChanged
}
)

Handling Timer Selection and displaying selected time in Text Widget

The selected duration is stored in the selectedDuration variable initially it will be 0 for hours,minutes and seconds duration, When the user selects a new duration from Cupertino Timer Picker, the onTimerDurationChanged callback is triggered which has callback duration value selected using which we can update the selectedDuration using setState to reflect the user’s selection.

Source Code – CupertinoTimerPicker Flutter

Output

flutter cupertinotimerpicker
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {

  Duration selectedDuration = Duration(hours: 0,minutes: 0,seconds: 0);

  void _showTimerPicker(BuildContext context){
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context){
          return Container(
            height: 200,
            color: CupertinoColors.white,
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [CupertinoButton(child: Text("DONE"), onPressed: (){
                    Navigator.of(context).pop();
                  })],
                ),
                Expanded(
                  child: CupertinoTimerPicker(
                     mode: CupertinoTimerPickerMode.hms,
                      initialTimerDuration: selectedDuration,
                      onTimerDurationChanged:  (Duration duration){
                       setState(() {
                         selectedDuration = duration;
                       });
                      }
                  ),
                )
              ],
            ),
          );
        }
        );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Selected Time ${selectedDuration.inHours} hours, ${selectedDuration.inMinutes % 60} mins, ${selectedDuration.inSeconds % 60} sec,'),
          SizedBox(height: 15,),
          ElevatedButton(onPressed: (){_showTimerPicker(context);}, child: Text("Show Time Picker"))
        ],
      ),),
    );
  }
}

Conclusion: This article introduced you to the Flutter Cupertino Timer Picker and showed you how to implement Time Picker in your flutter app in IOS style UI. You can further customize it to match the style of your app and use it to collect time-related input from your users.

References and Resources:

Related Article

Bottom Popup Cupertino action sheet flutter

easiest way to implement image picker in flutter

Date Time Picker in Flutter

File Picker in flutter

Google apis utilize in flutter

0
FLUTTER GOOGLE API
FLUTTER GOOGLE APIS

Hello guys, Welcome to Proto Coders Point. In this Flutter Article we discuss about Google apis Implement in flutter.

Examples of user-data APIs include Calendar, Gmail, and YouTube. 

Note: The only APIs you should use directly from your Flutter project are those that access user data via Google authentication. APIs that require service accounts should not be used directly from a Flutter application.

Direct use of service account-required APIs from a Flutter application is not advised. This necessitates the use of your application’s insecure shipping service credentials. We advise building an intermediary service in order to leverage these APIs.

Here describe use google api in flutter

Google APIs in flutter

Step 1 : Select the preferred API

The package’s API is listed on googleapis as a distinct Dart library using the name_version format. 

For an example let’s take youtube_v3 as an illustration.

In addition to being the class you must instantiate (see step 3), the Api class also exposes the scopes that stand for the permissions required to utilize the API. You can find the scopes available by looking under the Constants section of the YouTubeApi class. Use the youtubeReadonlyScope when authenticating the user to ask for permission to merely read an end-user’s YouTube data.

Import this library

import 'package:googleapis/youtube/v3.dart';

Step 2 : Turn on the API.

You need a Google project and an account on Google in order to access Google APIs. Additionally, you must turn on the desired API.

Using the console, enable an API for a project:

1) Visit the API Library for the Google Cloud console.

2) Choose the project you want to utilize from the list of projects.

3) Choose the API you want to activate from the API Library. Use the search bar and/or the filters if you need assistance finding the API.

4) Click ENABLE on the API page.


Step 3: Use the necessary scopes to authenticate the user

Users can authenticate with their Google identity by using the google_sign_in package. For each platform you want to support, you must configure sign-in.

Dependencies Within pubspec.yaml

dependencies:
  google_sign_in: 
  googleapis: 
import 'package:google_sign_in/google_sign_in.dart';

The desired permissions are supplied when the GoogleSignIn class is instantiated, as was covered in the previous section.

final _googleSignIn = GoogleSignIn(
  scopes: <String>[YouTubeApi.youtubeReadonlyScope],
);

To enable user authentication , adhere to the directions given by package:google_sign_in.

You must get an authenticated HTTP client after completing your authentication.


Step 4: Obtain an HTTP client that is authorized.

A GoogleSignIn extension method called authenticatedClient is offered by the extension_google_sign_in_as_googleapis_auth package.

import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';

OnCurrentUserChanged can be heard. You can design a client that is authorized if the event value is not null.

var httpClient = (await _googleSignIn.authenticatedClient())!;

When calling Google API classes, this Client instance already has the required credentials.


Step 5: Make the desired API class and use it.

Create the desired API type using the API, then call the methods, like in:

var youTubeApi = YouTubeApi(httpClient);

var favorites = await youTubeApi.playlistItems.list(
  ['snippet'],
  playlistId: 'LL',
);

The principles discussed on this page have a working implementation in the extension_google_sign_in_as_googleapis_auth example. We appreciate you joining us on a flutter journey! I hope you succeeded in finding what you sought.

Working with BLE devices in Flutter, Get List of BLE and Connect it.

0
Bluetooth Low Energy (BLE) In Flutter
Bluetooth Low Energy (BLE) In Flutter

In this flutter article, I’m excited to share an overview/baisc of what I have learnt whileworking with BLE in flutter application will provide you with flutter BLE code example with practical code simple, This flutter article on BLE might be a game changer.

Working with (Bluetooth Low Energy) BLE devices in flutter

Video Tutorial – BLE SCANNER

Flutter Blue Plus

A most popular package to work with Bluetooh Device in flutter is flutter_blue_plus package that provides Bluetooth Low Energy (BLE) functionality by using this package we can scan nearby bluetooth devices, connect with them & communicate with them.

Here is a step by step guide on how to work with BLE devices in flutter using flutter_blue_plus package.

Firstly we need to add BLE package into our flutter project follow below steps

1. Open pubspec.yaml file and under dependence section add

dependencies:
  flutter_blue_plus: ^1.16.2

2. Once package added you need to run below cmd to download the package as external dependencies

flutter pub get

3. To use flutter blue plue you need to import where required

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

Note:- Make sure you ask app users to accept bluetooth usage permission by prompt. Once users accepts the permission, you can start using mobile bluetooth into you flutter application.

Scan from BLE devices

Below is a snippet code to scan nearby BT devices

FlutterBluePlus flutterBlue = FlutterBluePlus.instance;

// Listens to BLE devices
flutterBlue.scanResults.listen((results){

// Hanlde discovered ble devices here

});

Connect to the devices

Once you find the available devices nearby you can connect to that particular devices using below method.

void connectToDevice(BluetoothDevice device) async{
    await device.connect();
}

Discover Services list

Don you know? each BLE devices has list of service that the device can provide, by connecting to in we can discover the list of services it has in it.

To fetch all the list of services that device has use below snippet code.

final services await device.discoverServices();

BLE Characteristics

Each services in BLE devices has list of it own characteristics, which is used to communicate with devices based on how it been manufactured. Fore Example:- Generic Access Services has list of BLS characteristics such as device name, MAC address etc.

Below is snippet code to list out characteristic of a services

for(var service in services){

  List<BlueToothCharacterictic> characteristics = service.characteristics;

}

Read Characteristics in BLE devices

Reading charactericistic retrive data from BT devices.

Create a Bluetooth Charactericistic Object then use read() method to perform read operation make sure to use await as read() is a asynchronous nature.

Snippet

BlueToothCharacterictic characteristics;

List<int> value = await characteristics.read();

//handle the value as needed

print(`Read Value: ${value.toString()}`);

Write Characteristics in BLE devices

Sending data to BLE devices to done by using write characteristics, We make use of write() methods make sure you use await with write() method.

You need to prepare the data to be sent as alist of integers, After the write operation you can listen for notification just to confirm that write was successful.

List<int> dataToSend = [0x01,0x02,0x03];

//write the data to characteristic
await characteristics.write(dataToSend);

Flutter BLE Scanner

Below is a source code, just an example how to implement BLE Scanner into Flutter Application

code

add dependencies in pubspec.yaml file

  flutter_blue:
  get: ^4.6.5
  permission_handler:

ble_controller.dart

The below Code have 2 main methods, One for scanning near by BLE ( Bluetooth Devices ) and another method is used for connecting to BLE devices.

import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class BleController extends GetxController{

  FlutterBlue ble = FlutterBlue.instance;
  
// This Function will help users to scan near by BLE devices and get the list of Bluetooth devices.
  Future scanDevices() async{
    if(await Permission.bluetoothScan.request().isGranted){
      if(await Permission.bluetoothConnect.request().isGranted){
        ble.startScan(timeout: Duration(seconds: 15));

        ble.stopScan();
      }
    }
  }

// This function will help user to connect to BLE devices.
 Future<void> connectToDevice(BluetoothDevice device)async {
    await device?.connect(timeout: Duration(seconds: 15));

    device?.state.listen((isConnected) {
      if(isConnected == BluetoothDeviceState.connecting){
        print("Device connecting to: ${device.name}");
      }else if(isConnected == BluetoothDeviceState.connected){
        print("Device connected: ${device.name}");
      }else{
        print("Device Disconnected");
      }
    });

 }

  Stream<List<ScanResult>> get scanResults => ble.scanResults;

}

main.dart

import 'package:ble_scanner_app/ble_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("BLE SCANNER"),),
        body: GetBuilder<BleController>(
          init: BleController(),
          builder: (BleController controller)
          {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  StreamBuilder<List<ScanResult>>(
                      stream: controller.scanResults,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Expanded(
                            child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: snapshot.data!.length,
                                itemBuilder: (context, index) {
                                  final data = snapshot.data![index];
                                  return Card(
                                    elevation: 2,
                                    child: ListTile(
                                      title: Text(data.device.name),
                                      subtitle: Text(data.device.id.id),
                                      trailing: Text(data.rssi.toString()),
                                      onTap: ()=> controller.connectToDevice(data.device),
                                    ),
                                  );
                                }),
                          );
                        }else{
                          return Center(child: Text("No Device Found"),);
                        }
                      }),
                  SizedBox(height: 10,),
                  ElevatedButton(onPressed: ()  async {
                    controller.scanDevices();
                    // await controller.disconnectDevice();
                  }, child: Text("SCAN")),

                ],
              ),
            );
          },
        )
    );
  }
}

building ble bluetooth scanner app in flutter

Conclusion

In this article, we learnt basic of BLE in flutter like how to discover list of BLE devices nearby, connecting to BLE Devices fetching services characteristic , reading & writing to device protocal in flutter application using flutter_blue_plus package.

Build a simple Express server – JS Express

0
build express js server in nodejs
build express js server in nodejs

Express.js in JavaScript. The Express.js is the most popular web framework used for building web applications and APIs in Node.js Project. In this article we will learn how to create express server with nodejs. Before you start, make sure you have Node.js installed on your system. If not, you can download it from the official website: https://nodejs.org/

1. Setup Node Project

Create a folder named express-server open the folder in your favorite code Editor (VSCode), then run below cmd to make it a Node Project.

#initialize a Node Project

npm init -y

This cmd will convert a normal folder into a node project by creating package.json file it holds your project meta-data.


2. Create a server file

In root directory of project, create a file by name index.js.

Now to make a Express Server application we need to download & install Node Express Module into the project.

Run below cmd to install ExpressJS

npm install express

now import it on top on index.js file to create Node Express Application

const express = require('express');

//create express app
const app = express();

3. Add Middleware

In our Node Project, Let’s use 2 middleware

  1. One is to parse incoming request with JSON payloads.
  2. Second is to parse incoming request with URL-encoder payloads
const express = require('express');
const app = express();

// parse incoming request to JSON payloads.
app.use(express.JSON());

//parse incoming request with URL-encoding 
app.use(express.urlencoded({extended:true});

4. Create an API router

Now lets create a root API that will send JSON data response whenever there is a request to root api.

app.get('/',(req,res)=>{

res.status(200).json({message:"API CALLED..!"})

});

5. Creating Express Server & Listen for server

Now let’s make a server to listen to a particular port may be let’s say post 3000 address i.e http://localhost:3000/

const port = 3000;

app.listen(port,()=>{
   console.log("Server listening to port 3000");
});

6. Start a server

To start Node Express Server, Open terminal/cmd prompt & run node index.js be being in root directory of project.

node index.js


7. Make a API request

Visit http://localhost:3000/ in your browser to see the API response.


Related Article

Books Directory Project wirh NodeJS – CRUD operation using Mongoose MongoDB

How does MERN Stack Work

JSON in 2 minutes (JavaScript Object Notation)

0
Javascriot object notation json
Javascriot object notation json

What is JSON?

JavaScript Object Notation(JSON) is a standard text based data format used in application development to send and receive data in JSON format, JSON is basically used to transfer sets of data from server to client or vise versa, Here data is formatted in key-value pair and separated by using commas.

Example of JSON data format

{"firstName":"Rajat", "lastName":"Palankar"}

JSON Array of Object Example

"employees":[
    {"firstName":"Rajat", "lastName":"Palankar"},
    {"firstName":"Manoj", "lastName":"Anvekar"},
    {"firstName":"Peter", "lastName":"England"}
]

Where are JSON been used?

Now a days, JSON data is been to build various applications throught out the world in IT field, Here are few common area where JSON is used:

  1. Web APIs: JSON is most popular format for data exchanging between web servers and client application and are commonly used in building API’s like for example Weather service, Payment gateway, social media platforms.
  2. Data Storage: JSON are also used in NoSQL databases like MongoDb and CouchDB. The database store JSON documents and make it suitable choice to make application flexible and schema-less data storage.

IoT (Internet of Things): Now a days JSON data is been used in IoT applications also mainly for exchanging data between IoT devices and servers. As JSON data is lightweight it makes it suitable for resource-constrained devices.

Mobile App Development: JSON is commonly used in mobile app development for data storage, communication with APIs, and configuration files.

Data Transformation: JSON is used in data transformation processes where data is converted from one format to another. For example, ETL (Extract, Transform, Load) processes often involve transforming data into JSON format for easier processing.

and many more


Advantage of using JSON

  • It is a light weight database standard, so data transmission is much faster.
  • It can be used on all platforms.
  • It is supported by all programming langauges.

Data types supported in JSON

  • String
  • Number
  • Arrays
  • null
  • Boolean
  • Objects

JSON Methods in Javascript

JSON,parse(): Takes JSON String and convert it into JavaScript Object.

JSON.stringify(): Convert JavaScript Object(JSON) into JSON String (Useful while sending over the network).


JSON Syntax and Example

JSON syntax and example
{
  "name": "Rajat Palankar",
  "age": 30,
  "email": "rajatpalankare@example.com",
  "isSubscribed": true,
  "hobbies": ["reading", "hiking", "swimming"],
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "zipcode": "12345"
  }
}

In this example:

  • JSON data is enclosed in curly braces {}.
  • Data is represented as key-value pairs, where the key is a string enclosed in double quotes, followed by a colon :, and then the corresponding value.
  • Strings must be enclosed in double quotes.
  • Numeric values don’t need quotes.
  • Boolean values are true or false.
  • Arrays are represented using square brackets [] and can contain multiple values of different types.
  • Objects (nested structures) can be used as values for keys, creating a hierarchical structure within JSON.

Recent Articles

How to read JSON file in flutter dart

Flutter Auto Create Model from JSON Files

How to parse JSON Data in Flutter

How to convert array to collection in Javascript

How is Artificial Intelligence Shaping the Future of Ecommerce?

0
AI in ecommerce application

Since its introduction, AI (Artificial Intelligence) has successfully found its applications in every industry and landscape. The ecommerce industry is no different. We have seen unprecedented growth of the ecommerce industry lately. 

Some eye-opening facts and figures reflect this unprecedented evolution of the ecommerce industry. 

Nearly 24 million ecommerce stores are active online. In 2021, the ecommerce sales grew by 27.6%. Moreover, in the same year, ecommerce sales saw a significant boom worldwide, and purchases worth $4.1 trillion were made online. 

This huge figure accounted for 19% of the worldwide sales. The revenue of the worldwide e-commerce industry is expected to grow to $8.1 trillion by 2026.

While several reasons played a role in the evolution of the e-commerce landscape, you can’t overlook the role of AI in this entire phenomenon. The ecommerce landscape is based on technology, and ecommerce retailers want to get the most out of technology to ensure an excellent online shopping experience and an exceptional increase in revenue. 

AI and its subsets like Machine Learning, NLP (Natural Language Processing), and Computer Vision are helping ecommerce retailers make it possible. The involvement of AI in the ecommerce landscape is already opening the gateway for us to the future. Thanks to AI, things that were considered impossible a few years back are now possible. 

Here is how AI is shaping the future of the ecommerce landscape. 

Visual search is the most obvious example of AI’s involvement in the ecommerce landscape. Customers often fail to find their desired products online through conventional search until they have all the necessary details. The voice search method may also fail to work in such a scenario. Conversely, the visual search method can help users find their desired merchandise easily. It is often observed that consumers like to take pictures of products they want to buy. 

They can easily find the exact product online and the vendor selling it with the help of the image of merchandise. All they need to do is perform a reverse image search online. Performing an image reverse search will help them find the exact product and other products that fall in the same category with better pricing. 

While reverse picture search utilities are available to help users find products, many ecommerce stores also offer the visual search feature to help users find their desired merchandise.

AI Chatbots

AI is not only limited to the visual search when it comes to its involvement in the AI landscape. AI has led to the development of NLP (Natural Language Processing), which enables computers to interact with humans and respond to them meaningfully. This NLP works behind AI chatbots that are available on ecommerce stores to respond to the queries of users. This application of AI has enabled ecommerce vendors to hire human resources for more complex human tasks.

chatgpt

In addition, AI chatbots are available to respond to queries 24/7, which means users can get quick answers without waiting for someone to view and answer their queries. This possibility helps ecommerce vendors ensure optimum user experience. Moreover, AI chatbots can also suggest various products. In case of complicated queries, these chatbots can connect customers to human customer support representatives capable of handling the matter more efficiently.

Automated Reminders

It is pretty frustrating for ecommerce retailers when a user spends significant time on a product page or adds a few products to the cart but leaves the site without performing the desired action, i.e., purchase. AI offers help to e-commerce vendors by letting them generate automated reminders for such users and enticing them to purchase products they have left in abandoned carts. These automated reminders are sent to users through email. The email copies sent as automated reminders feature captivating words.

AI in ecommerce

These reminders can help users realize what they are actually missing by not purchasing the products. Moreover, these automated reminders may feature discount codes to compel them to visit the website again and reach the checkout page to complete the purchase. These automated reminders may also request feedback to enquire about the reasons behind the abandoned cart. Simply put, AI-backed automated reminders can help ecommerce retailers boost conversions. 

Personalized Shopping Experience

Everyone likes special treatment while shopping for products from a brick-and-mortar outlet or an ecommerce store. Brick-and-mortar outlets hire sales executives who guide buyers about various products and recommend products based on their requirements, purchase history, and preferences. Online retailers can use AI and machine learning to boost their conversions. Many e-commerce retailers use it to increase their sales and achieve fruitful results. 

AI and machine learning help e-commerce retailers understand the purchase patterns of existing users. Moreover, virtual shopping assistants are employed to understand the requirements of newcomers. An understanding of purchase patterns helps ecommerce retailers upsell and cross-sell products easily. This process impresses customers and helps e-commerce retailers increase their revenue. Hence, an AI-backed personalized shopping experience is a win-win solution for both parties.