Home Blog Page 2

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
    );
  }
}

14 Rules to follow to become a professional flutter developer

0
How to Become a Professional Flutter Developer

Hi Guys, Welcome to Proto Coders Point, In this Flutter Article let’s check how to become a professional flutter developer by just following this coding rules in flutter.

How to become a professional flutter developer

1. Always use a const keyword for static data.

When any widget using static data which will never change in runtime , it’s better to use const on those widget or dataType.

return Scaffold(
      body: Container(
         child: Column(
           children: const [
             Text("This is static Text"),
             Text("so use const keyword ")
             // Always use a const for static type data
           ],
         ),
      )
    );

2. Use right widget as right place.

Below Example is not the right way to give padding.

Container(
        padding: EdgeInsets.all(10),
         child: Text("This is static Text"),
)

Flutter app is app an widget, but using right widget matters. In Above Example, I am using Container widget just to give padding to a child does not make sense right, Flutter has padding widget use that instead.

Padding(
        padding: const EdgeInsets.all(10.0),
        child: Text("This is static Text"),
 )

3. Make use of setState() properly for rebuild update.

If you are not using any state management plugin like flutter bloc, provider, GetX. They you might be using setState to rebuild the widget tree to update the date update.

Basically setState() will revuild the whole widget treee, just to make a small change in textField.

Instead create a seperate widget and use StatefulBuilder so that on setState only the particular widget tree get rebuild instead of whole widget tree.

Example:

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

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  // Do
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Text('${_counter}'),
        ElevatedButton(
            onPressed: () => {
                  setState(() {
                    _counter++;   // this will rebuild whole widget tree
                  })
                },
            child: Text("Click")),
        NewWidget()
      ],
    ));
  }

  Widget NewWidget() {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return Column(
          children: [
            Text('${_counter}'),
            ElevatedButton(
                onPressed: () => {
                      setState(() {
                        _counter++; // on button click only this widget will get updated
                      })
                    },
                child: Text("Click"))
          ],
        );
      },
    );
  }
}

4. Use private variable/method.

Keep habit of using private variable. In flutter Dart doesn’t have the keywords like public, protected, and private. If an identifier starts with an underscore _, it’s private variable in dart.

This is not the right way

class Registration{
  String name,email,phone;
  
  Registration(
      {
        required this.name,
        required this.email, 
        required this.phone
      });
  
}

The Right way to use provide variable

class Registration{
  String _name;
  String _email;
  String _phone;

  Registration(
      {
        required String name,
        required String email,
        required String phone
      }) : _name = name, _email = email, _phone = phone;

}

5. Create seperate Method for event.

Avoid using implementing method or any event inside a widget itself, It’s not a good practice in flutter application development For Eg: Performing any event or action when user press a button, It Ok if event is a small task, if it a long code on event like calling a API to get data from server then it better create a seperate method outside a widget.

Example:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _doSomeThing(){
    print("perform your button press action here");
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Text('${_counter}'),
        ElevatedButton(
            onPressed: ()=> _doSomeThing(),
            child: Text("Click")),
      ],
    ));
  }
}

6. Use Nullable the right way.

THe best feature of dart language is null safety I wrote a complete article on flutter null safety check it out to learn in detail

Don’t Do
Do

7. Internalization your flutter app.

Avoid using Hardcoded string in app. By implementing Internationalization in flutter app at the beginning of development is better, because one your app starts to grow, then to update small changed in-app then in one place you can easily search and update/replace the string easily.

Example:

Don’t do

Text("This is hard coded Text")
Text(
  AppLocalizations.of(context)!.AppName,     //
)

8. Don’t use var at all declaration.

use exact datatype, when you know it value type.

Exmaple: if a variable is of type number then it better to use int instead of var.

Eg:

String name = 'Rajat';
int age = 26;


9. Keep Flutter Theme & Page Routes in seperate file.

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(),
    );
  }
}

10. Use stateless widget the right way.

using StatefulWidget, unnecessarily all over the flutter app is not the right way to build flutter application, Use Stateless Widget where there are not rebuild or update required (widget data is fully static).


11. Don’t forget retrun type declaration in functions

Always give a return type to function

dart return type declaration function
Don’t Do – Function without return type declared
dart return type declaration function
Do – Always declare a return type to a function

12. To Compose String use Interpolation

With string variable instead of using “+” to concate strings in variable, make use of interpolation in dart language.

dart interpolation
In this example + is been used to concate string into variable
dart interpolation
In this example interpolation ${var}, is used.

13. using cascade operator in dart

With one object when you run sequence of operation make use of cascade operation (..) double dot operators.

dart cascade operator
dart cascade operator example
Don’t Do
cascade operator in dart example
Do

14. Giving naming convention in dart the right way

Don’t
dart naming convention
Do

What is different between Packages & Plugins in Flutter

0
Different between Packages & Plugins Flutter
Different between Packages & Plugins Flutter

Hi Guys, Welcome to Proto Coders Point. In this flutter article let’s see the different between package & plugin in flutter.

Flutter Plugin

A Plugin will contain both a language + native code language, i.e Android (java, kotlin), iOS (Swift/Objective C) & Web, which together makes it called as plugin.

A specialized dart plugin that contain code written in dart combined with one or more platform specific (native) implementation, best example in flutter for plugin is url_launcher & flutter share plugin.

url launcher, it contain support for all platform (Android, iOS, Web & now even for desktop based application).

The code that are behind this plugin are native code, This native code are build by respective developers (android, iOS, web, desktop) & thus when this plugin are used in flutter application & run on any native platform, It will work perfectly smooth, Which makes app compactable on any platform and userfriendly.

Flutter Package:

A Package are fully written with one programming language, flutter package as example are written using dart prgramming language.
"If a Package uses any plugins in it, then it will still be called as package itself", because If I talk about development of package, you are not creating any plugin on your own, In fact you are just using plugins created by some other developer & creating yours own flutter package.

So your app need package, They’re helpful additions that make lots of things easier, some of those packages are pure dart code, those are called as package. In other hand other also includes some Java, Kotlin, Swift, JavaScript and those we call as Plugins.

Solution – unable to connect to server postgresql pgadmin

0
unable to connect to server postgresql using pgadmin

Hi Guys, Welcome to Proto Coders Point. This article is on the solution i.e “pgadmin unable to connect to server”, “could not connect to server: Connection refused”.

Here are 2 issue you may face while connecting to postgresql server using pgadmin.

1. Could not connect to server: Connection refused

pgadmin postgresql connection refused solution

2. Unable to connect to postgres server at IP port 5432 failed: timeout expired

pgadmin postgresql connection timeout expired

Solution

Solution 1 – Check if postgresql server is active

run below cmd to check postgresql status

sudo service postgresql status
postgresql check status

If it InActive, restart postgresql

sudo service postgresql restart

Solution 2: enable postgres to allow remote connections

By default postgresql remote connection is disabled for globally accessing db using server IP & can only by accessed locally on server itself.

ss -nlt | grep 5432

This should give response as running on global 5432, i.e. 0.0.0.0:5432. This means that psql is now enabled for remote access.

check postgresql listening post

Check out this article to enable postgres to allow remote connections.


Solution 3: All PostgreSQL port 5432 Inbound rules on cloud instance

Check if you have Added Inbound rules for allowing incoming traffic to port 5432, Add Inbound rules, as shown in below image.

add inbound rules on aws server for port 5432

After postgres configuring as soon in above steps, you will sure be able to connection postgresql server using pgadmin.

pgadmin postgresql connect

Best To Buy from Amazon