Home Blog Page 34

Flutter make Get/Post request using GetX Package

0
Flutter GETPOST request using GETX Library

Hi Guys, Welcome to Proto Coders Point, In this flutter Article let’s learn How to make Get/Post request in flutter app by using GetX package GetConnect() class.

What is GetX in Flutter

In Flutter GetX is an multi functiional powerful library which is open source to use in flutter app.

GetX provides massive high performance in teams of state management in flutter, route management, dependencies injection & basic functionalities such as showing snackbar, dialog Box popup, getStorage for storing data as mini database, Internationalization & much more can be used by just adding one line of code.

Although flutter getx has multiple feature in it, Here GetX library is built in such a way that each feature has it’s separate container & thus only the used once in your flutter app is been compiled.

Therefore, Getx library is very light weight as it does not increase app size much.

GET/POST request in flutter

In flutter app, we can make internet calls i.e GET/POST request by using GETX GetConnect class, you will be suprised by the lines of code your need to write to make Get/Post request.

Step to make GET/POST request using GETX Flutter library

1. Install GetX Dependencies

In your flutter project to use GetX you need to install it , Run below commond in IDE terminal

flutter pub add get

2. Import get.dart

Now, Once getx package is added as dependenies library, to use it, import where require Eg: main.dart

import 'package:get/get.dart';

3. Create Instance of GetConnect Class

Now, you need an instance of GetConnect() class. Let’s create it.

 final _getConnect = GetConnect();

now, use this GetConnect instance to make GET/POST requests.


4. A Function that makes GET Request

 void _sendGetRequest() async {
    final response =
    await _getConnect.get('API URL Here');

    if (kDebugMode) {
      print(response.body);
    }
  }

5. A Function That makes POST request

 void _sendPostRequest() async {
    final response = await _getConnect.post(
      'http://192.168.29.167:3000/register',  // rest api url
      {
        'username': 'rajat123@gmail.com',
        'password': '554433#221100',
      },
    );

    if (kDebugMode) {
      print(response.body);
    }
  }

Flutter Get/Post Request – Complete Example

I have created a backend NodeJS API, Which simply stores the data in Mongodb database when API Router is been triggered from frontend.

In this Article our frontend is flutter app, which has 2 TextField (username & password) and a Button (basic registration form), when button clicked, data entered in TextField is been sent through POST method of Flutter GetX library to backend NodeJS server which while store the entered data into MongoDB database.

api call using getx flutter

Nodejs Backend create user store user data in database
Nodejs Backend create user store user data in database

Get NodeJS Backend code from my github repository


MongoDB data stored screenshot

nodejs api stored data in mongodb database
nodejs api stored data in mongodb database

Flutter App Complete Source Code

main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.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> {

  final _getConnect = GetConnect();
  final TextEditingController emailText = TextEditingController();
  final TextEditingController passwordText = TextEditingController();

  // send Post request
  void _sendPostRequest(String email,String password) async {
    final response = await _getConnect.post(
      'http://192.168.29.167:3000/register',
      {
        'username': email,
        'password': password,
      },
    );
    if (kDebugMode) {
      print(response.body);
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(30),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: emailText,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Enter Email Or Username",

                ),
              ),
              SizedBox(height: 5,),
              TextField(
                controller: passwordText,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: "Enter Password",

                ),
              ),
              ElevatedButton(
                  onPressed: ()=>_sendPostRequest(emailText.text,passwordText.text),
                  child: const Text('Register')),
            ],
          ),
        ),
      ),
    );
  }
}

What’s new in Flutter 3.3

0
What's New in Flutter 3.3
Flutter 3.3

Hi Guy’s Welcome to Proto Coders Point. Flutter have recently announced it thrilled & amazing flutter 3.3 which focuses on refinement of recent release i.e flutter 3.

Flutter 3.3 new features

1. Selectable Text in flutter

Till now Flutter did not support text selection to copy the content shown in app, Flutter Web App running on browser user were not able to copy the text from widgets.

Now with flutter 3.3, They have introduced a new widget i.e. SelectableArea, when used flutter user will be able to select on both mobile & web app.

Example:

Flutter Selectable Text Widget example

Learn more on Flutter selectableText widget.


2. Trackpad Input

Flutter 3.3 now support for trackpad input. This not only support smoother & richer control, but also reduces misinterpretation in certain situation.

For Example: check out Drag a UI element page in the Flutter cookbook, Scroll to bottom of page to get dartpad instance and perform the following steps:

  • Size window smaller so the the upper part present a scrollbar at side.
  • now, hover over the upper part.
  • use a trackpad to scroll.
  • before you have install 3.3 flutter sdk, scrolling on the trackpad drags the item because flutter was dispatching general events.
  • Now, do the same thing after installing flutter 3.3, scrolling on a trackpad correctly scrolls the list because flutter is scrolling gesture, which isn’t recognized by the cards but is recogized by the scroll view.

3. Flutter Scribble

Flutter now came up with an amazing feature i.e. Scribble handwritting text input, Instead of using keyboard to type text into the textfield, If you have a stylus pen, simple use stylus on TextField, flutter will automatically read the freehand drawing from textField & convert it into text.

flutter scribble textfield

4. Text Input

From platform TextInputPlugin, They release an ability to ceceive granular text updates, Previously TExtInputClient only delivered the new editing stat which no delta between the old and newm TextEditingDeltas and the deltaTextInputClient fill the information gap.

Having access to there eltas allows you to build an input field with styled ranges that expands and contract as you type.

Learn more Check out Rich Text Editor Demo

5. Flutter Material Design 3

Flutter team continues to add more and more material design componets in flutter, with flutter3.3 update they have added Material Design 3. This update includes IconButton, Flutter Chips, different variants to add appbar in flutter

6. Flutter IconButton

In Material Design, We have IconButton been added, This are picture printed on Material Widget that react to touches by filling with color,

Commonly Icon Button are very useful in Appbar actions field, and can even be used in many places as well.

flutter icon button

What is GraphQL? Will it replace RESTAPIs

0
What is GraphQL Will it Replace RESTFUL API

What is GraphQL?

Basically GraphQL is a Query language used to develop API’s, GraphQL is been developed by Meta(Facebook). It gives power to client to ask for any data as per client need, it provides ful described data in the API.

Usually GraphQL servers works as a middleware, it sits between client side and backend services to communicate data within.

It can aggregate multiple RESTfull API request into a single Query.

It also support various queries like, mutations(used for data modification before sending to front end client) and subsriptiions(schema modification on receiving notifications).

Different between RESTAPI and GraphQL

REST APIGraphQL
Architectureserver-drivenclient-driven
Organized in terms ofEnd PointSchema & type System
OperationsCRUD OperationQuery mutation Subscription
Data fetchingFixed data with multiple api callsSingle API call
PerformanceMultiple network calls will increase response timeFaster
Development speedMediumSuper Faster
Learning curveEasily to LearnDifficult to learn
Self – documentingNoYes
File UploadingSupportedNot Supported
Web CachingYesNo, caches. but using libraries we can.
Stabilitybetter choise for complex queriesless error prone, automatic validation
Use CasesSimple App’s monolithic architectureBest for microservices application, Mobile Applications

How GraphQL Query request

Will graphQL replace restful api

As you all hearing a lot boom about the popularity gain of GraphQL and it ability in building efficient, powerful & flexible API’s as compared with REST.

REST is a one among famous API development technology but after launch of GraphQL in 2015 by FACEBOOK(META), It got boom in market and many API developer are trying to get upgraded in this GraphQL.

Pros and Cons of RestAPIs and GraphQL

RestAPI’s

proscons
Supports different data formats (Html, JSON, etc.)An annoying and confusing pagination system
Resources efficiencyDifficulty to get issues general information
Better scalability

GraphQL

proscons
Eliminates over-fetching & under-fetching.Lacks built-in caching.
Provides consistent, uniform dataComplicated error handling.
Speeds up the development processLacks industry adoption & support.

Mongodb findOneAndUpdate return old data – Solution

0
mongodb findoneandupdate return updated
mongodb findoneandupdate return updated

Hi Guys, Welcome to Proto Coders Point. When you execult findOneAndUpdate by default mongodb return an unaltered data/document i.e. The query will the original data before updating. Mongodb findOneAndUpdate return old data.

How to Mongodb query findOneAndUpdate return updated data

I want mongodb findOneAndUpdate to return updated value.

If you want to newly updated document returned then you need to just make use of additional argument in the query i.e. A Object with new property and set it to true.

Solution

Just pass {new: true}, and this will return the updated document of mongodb findOneAndUpdate query.

Eg:

let updateStatus = await Model.findOneAndUpdate({ _id: id }, { status }, { new: true });
console.log(updateStatus);

Flutter 3.3 – Scribble Handwritting text input on textField

0
Flutter Scribble HandWritting Text Input on TextField

Hi Guy’s Welcome to Proto Coders Point, This Article is on flutter 3.3 new feature i.e scribble text input.

Flutter now came up with an amazing feature i.e. Scribble handwritting text input, Instead of using keyboard to type text into the textfield, If you have a stylus pen, simple use stylus on TextField, flutter will automatically read the freehand drawing from textField & convert it into text.

Flutter Scribble Example

flutter 3.3 scribble
Flutter Scribble feature on any textField Widget

Currently this feature is enabled on IPadOS using Apple Pencil.

Flutter has by default enabled this scribble feature on CupertinoTextFieldTextField, and EditableText widgets Flutter 3.3.

To enable scriible freehand drawing on TextField for FreeHand Text Input, flutter developer need to just upgrade flutter sdk to 3.3 version and rebuild the flutter app and distribute the app to the users.

Flutter Textfield Credit Card Number Input Format

0
credit card number input format flutter

Hi Guy’s Welcome to Proto Coders Point. In this flutter tutorial let’s learn How to create textfield which accept number in credit card format, I mean to say after every 4 digits entered by user there is a space.

For Example: 5487 5485 1122 4455

Our Flutter TextField will display entered credit card number as above format.

Credit Card Input Format in flutter app

In Flutter TextFormField Widget, We have a very useful property i.e. inputFormatter:[], By using it we can validate & Format our input TextField.

1. User should be able to enter only Whole Number (0 – N), He should not be able to enter special symbol’s like (. or ,) from number keyboardType. Therefore in inputFormatter we can use FilteringInputFormatter

FilteringTextInputFormatter.digitsOnly

2. User should be able to enter max 16 character in textField, Therefore in inputFormatter we can use LengthLimitingTextInputFormatter

Debit/Credit Card Number will be of 16 character length

LengthLimitingTextInputFormatter(16)

3. A Class that return’s enter credit card number by giving space after every 4th digits.

Call the below called inside inputFormatters:[]

// this class will be called, when their is change in textField
class CreditCardNumberFormater extends TextInputFormatter{
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if(newValue.selection.baseOffset == 0){
      return newValue;
    }
    String enteredData = newValue.text;   // get data enter by used in textField
    StringBuffer buffer = StringBuffer();

    for(int i = 0;i <enteredData.length;i++){
      // add each character into String buffer
      buffer.write(enteredData[i]);
      int index = i + 1;
      if(index % 4 == 0 && enteredData.length != index){
        // add space after 4th digit
        buffer.write(" ");
      }
    }
   
    return  TextEditingValue(
      text: buffer.toString(),   // final generated credit card number
      selection: TextSelection.collapsed(offset: buffer.toString().length) // keep the cursor at end 
    );
  }

}

Flutter TextFormField InputFormatters Example:

TextFormField(
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  CreditCardNumberFormater(),
                  LengthLimitingTextInputFormatter(16)

                ],
...........
.......
.......
.......
),

Complete Source Code – Flutter TextFormField Credit Card Formatters

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {

  var themeSetting = ThemeData(      // Always Create a select variable to device Theme
      primarySwatch: Colors.blue,
      textTheme: TextTheme(),
      primaryColor: Colors.green
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter',
      theme: themeSetting,
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
       title: Text("Credit card input format")
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Form(
          child: Column(
            children: [
              TextFormField(
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,    // allow only  digits
                  CreditCardNumberFormater(),                // custom class to format entered data from textField
                  LengthLimitingTextInputFormatter(16)       // restrict user to enter max 16 characters

                ],
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    border: InputBorder.none,
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0)
                    ),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    hintText: "Enter Credit Card Number",
                    prefixIcon:  Padding(
                      padding: EdgeInsets.only(right:8.0),
                      child: Icon(Icons.credit_card),
                    ),
                  filled: true,
                  fillColor: Colors.grey[350]
                ),
              )
            ],
          ),
        ),
      )
    );
  }
}


// this class will be called, when their is change in textField
class CreditCardNumberFormater extends TextInputFormatter{
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if(newValue.selection.baseOffset == 0){
      return newValue;
    }
    String enteredData = newValue.text;   // get data enter by used in textField
    StringBuffer buffer = StringBuffer();

    for(int i = 0;i <enteredData.length;i++){
      // add each character into String buffer
      buffer.write(enteredData[i]);
      int index = i + 1;
      if(index % 4 == 0 && enteredData.length != index){
        // add space after 4th digit
        buffer.write(" ");
      }
    }
   
    return  TextEditingValue(
      text: buffer.toString(),   // final generated credit card number
      selection: TextSelection.collapsed(offset: buffer.toString().length) // keep the cursor at end
    );
  }
}