Home Blog Page 34

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

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.