Home Blog Page 26

List in dart – Useful List methods/functions in Dart

0
dart list & it's inbuilt method
dart list

Before using Dart List, you should be aware of the following details:

  • Dart supports two types of lists: fixed-length lists and growable lists.
  • The dart list must allow for duplicate values.
  • Dart list is an ordered collection that keeps the insertion order of the items.
  • While an operation on the list is being performed, changing the length of the list will break the operation.

What exactly is a list in dart language

The List datatype in Dart programming is similar to arrays in other programming languages. A list is used to represent a group of objects. It is an ordered collection of objects. Dart’s core libraries are responsible for the existence, creation, and manipulation of the List class, An ordered collection of objects.

In a Dart how do you define a list?

The Dart list resembles JavaScript array literals. The syntax for declaring the list is as follows. All elements in the Dart list are stored inside square brackets ([]) and separated by commas (,).

Syntax of a Dart List:

Dart in List is defined using this [] .

List listName = [1,2,3,4,5];

Dart List Properties

1. First

The First element of the list is returned by this method.

Syntax : List.first

void main() {
  List listName = [6,1,2,3,4,5];
  listName.first;
  print("$listName .first is the List's first element");
}

Your desired OutPut show below :
6 is the List's first element.

2. Last

The Last element of the list is returned by this method.

Syntax : List.last

void main() {
  List listName = [6,1,2,3,4,5];
  listName.last;
  print("$listName.last is the List's first element");
}

Your desired OutPut show below :
5 is the List's first element.

3. isEmpty

If the collection has at least one element, it returns false.

Syntax : List.isEmpty

void main() {
  List listName = [];
  print("List is Empty : ${listName.isEmpty}");
}

Your desired OutPut show below :

List is Empty : true

void main() {
  List listName = [6,2,3,4,5];
  print("List is Empty : ${listName.isEmpty}");
}

Your desired OutPut show below :
List is Empty : false

4. isNotEmpty

If the collection has at least one element, this method returns true.

Syntax: List.isNotEmpty

void main() {
  List listName = [];
  print("List is NotEmpty : ${listName.isNotEmpty}");
}

Your desired OutPut show below :
List is NotEmpty : false

void main() {
  List listName = [];
  listName.add(12);
  print("List is NotEmpty : ${listName.isNotEmpty}");
  print("List value is : ${listName}");
}

Your desired OutPut show below :
List is NotEmpty : true
List value is : [12]

5. Length

Returns the size of the list.

Syntax: List.length

void main() {
  List listName = [6, 1, 2, 3, 4, 5];
  print("The list's length is ${listName.length}");
}

Your desired OutPut show below :
The list's length is 6

6. reversed

This method produces an iterable object containing the contents of the list in reverse order.

Syntax : List.reversed

void main() {
  List listName = [6, 1, 2, 3, 4, 5];
  print("The reverse order of the list is : ${listName.reversed}");
}

Your desired OutPut show below :
The reverse order of the list is : (5, 4, 3, 2, 1, 6)

7. single

Check the list and return a single element if there is just one in the list.

Syntax: List.single

void main() {
  List listName = [6];
  print("There is only one item in the list, and its value is : $listName.single.");
}

Your desired OutPut show below :
There is only one item in the list, and its value is : 6

Insert element in the Dart List

Dart supports a variety of techniques for adding items to lists, which are used to insert elements into lists.

These techniques are listed below.

  1. add()
  2. addAll()
  3. insert()
  4. insertAll()

Let’s go through this one by one and check how to add element’s into dart list.

add()

This add() function adds the supplied value to the end of the list. It can only add one entry at a time and then return the changed list object.

Syntax : listName.add(element)

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("The list element's value is : ${listName}");
  listName.add(12);
  print("After the list value, add the : ${listName}");
}

Your desired OutPut show below :
The list element's value is : [1, 2, 3, 4, 5]
After the list value, add the : [1, 2, 3, 4, 5, 12]

addAll()

This addAll() function is used to insert numerous values into the supplied list. Each value is separated by commas and contained by a square bracket ([value]).

Syntax : listName.addAll([v1,v2,v3,v4,v5,…….n]);

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List element value is :${listName}");
  listName.addAll([12, 13, 14, 15, 16]);
  print("List an addAll the element after the list value is :${listName}");
}

Your desired OutPut show below :
List element value is :

[1, 2, 3, 4, 5]

List an addAll the element after the list value is :

[1, 2, 3, 4, 5, 12, 13, 14, 15, 16]

insert()

This insert() function is used to add a list entry at a specific index. The index position of the value to be added in the list can be specified.

Syntax : listName.insert(index,value);  

The syntax in the index variable assigns the specific index value that you must assign, and value into set specific index into desired value.

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List element value is :${listName}");
  listName.insert(2, 100);
  print("List element after insert the element :${listName}");
}

Your desired OutPut show below :
List element value is :

[1, 2, 3, 4, 5]
List element after insert the element :
[1, 2, 100, 3, 4, 5]

insertAll()

insertAll() is used to insert multiple values from the specified index point. It accepts an index position and a list of values as arguments and insert all the item into the list from specified index point.

Syntax :  listName.insertAll(index,listOfValue)

The syntax in index specifies a certain list of index values, and list of values specifies this type of [] list.

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List element value is :${listName}");
  listName.insertAll(0, [6, 7, 8, 9, 10]);
  print("List contains item after update  :${listName}");
}

Your desired OutPut show below:
List element value is :

[1, 2, 3, 4, 5]
List contains item after update:

[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

Dart update list item

The dart programming language has an Update list, which we may edit by simply accessing its element and assigning a new value at that position.

Syntax :  listName[index]=newValue;

You may also use the following properties to update one or more items in a List:

The item’s index

Eg:

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List contains item before update :${listName}");
  listName[3] = 100;
  print("List contains item after update  :${listName}");
}

Your desired OutPut show below :
List contains item before update :  [1, 2, 3, 4, 5]
List contains item after update  :  [1, 2, 3, 100, 5]

replaceRange

To delete items from a range, use the replaceRange() function, then insert others.

Eg:

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List contains item before update :${listName}");
  listName.replaceRange(1, 2, [1000]);
  print("List contains item after update  :${listName}");
}

Your desired OutPut show below :
List contains item before update : [1, 2, 3, 4, 5]
List contains item after update  : [1, 1000, 3, 4, 5]

Remove the list elements

Dart offers the following methods for removing list items:

  1. remove()
  2. removeAt()
  3. removeLast()
  4. removeRange()

Let’s use the above method and learn how to remove element from dart list.

remove()

removes() function removes one entry from the provided list at a time. As an argument, it accepts elements. If there are several occurrences of the supplied element in the list, it eliminates the first occurrence.

Syntax : listName.remove(value);  

void main() {
  List listname = [1, 2, 3, 4, 5];
  print("List contains item before remove list item :${listName}");
  listName.remove(5);
  print("List contains item after remove list item  :${listName}");
}

Your desired OutPut show below :
List contains item before remove list item : [1, 2, 3, 4, 5]
List contains item after remove list item  : [1, 2, 3, 4]

removeAt()

It returns an element that was removed from the provided index point.

Syntax : listName.removeAt(int index); 

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("Before removing an item from the list, Item in the list : ${listName}");
  listName.removeAt(3);
  print("After removing an item, the list includes it. At the top of the list :           ${listName}");
}

Your desired OutPut show below :
Before removing an item from the list, Item in the list : [1, 2, 3, 4, 5]
After removing an item, the list includes it. At the top of the list : [1, 2, 3, 5]

removeLast()

The removeLast() function is used to remove the list’s last element.

Syntax : listName.removeLast; 

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List contains item before removeLast list item :${listName}");
  listName.removeLast();
  print("List contains item after removeLast list item  :${listName}");
}

Your desired OutPut show below :
List contains item before removeLast list item :[1, 2, 3, 4, 5]
List contains item after removeLast list item  :[1, 2, 3, 4]

removeRange()

The item inside the provided range is removed using the removeRange() function. It takes two arguments: start and end indexes.

Syntax : listName.removeRange(startIndex ,endindex);

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("Before deleting an element, the list includes the following item : ${listName}");
  listName.removeRange(1, 3);
  print("After removing the element, the list contains the following item : ${listName}");
}

Your desired OutPut show below :
Before deleting an element, the list includes the following item : [1, 2, 3, 4, 5]
After removing the element, the list contains the following item : [1, 4, 5]

How to shuffle a list in dart

shuffle()

Shuffles a list randomly. By giving start and end, a sub-range of the list can be shuffled; if start and end are omitted, they default to the list’s start and finish. If random is not specified, a new instance of the random variable is created.

The dart list shuffle() function reorganizes the order of elements in a sequence, such as a list. The shuffle() function returns the modifications to the existing list rather than a new list.

Syntax : listName.shuffle();

void main() {
  List listName = [1, 2, 3, 4, 5];
  print("List before using shuffle :${listName}");
  listName.shuffle();
  print("List after using shuffle :${listName}");
}

Your desired OutPut show below :
List before using shuffle :[1, 2, 3, 4, 5]
List after using shuffle :[4, 2, 1, 3, 5]

How to Convert List to Map in dart

asMap()

This function asMap() returns a map representation of the supplied list. The indices would be the key, and the list components would be the value.

Eg:

void main() {
  List<int> listName = [1, 2, 3, 4, 5];
  print("List before convert asMap :${listName}");

  Map<int, int> convertToMap = listName.asMap();
  print("List after convert asMap :${convertToMap}");
}

Your desired OutPut show below :
List before convert asMap :[1, 2, 3, 4, 5]
List after convert asMap :{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}

take()

This take() function returns an iterable starting at index 0 and ending at the count specified from the given list.

Syntax : listName.take(value);  

void main() {
  List listName = [1, 2, 3, 4, 5];

  print("List Contains value :${listName}");
  print("List Contains specific value :${listName.take(2)}");
}

Your desired OutPut show below :
List Contains value : [1, 2, 3, 4, 5]
List Contains specific value : (1, 2)

skip()

This skip() function skips the elements of the list beginning at index 0 and ending at count and returns the remaining iterable from the provided list.

Syntax : listName.skip(value);  

void main() {
  List listName = [1, 2, 3, 4, 5];
  
  print("ListConatins value :${listName}");
  print("List Contains skipped value :${listName.skip(2)}}");
}

Your desired OutPut show below :
ListConatins value :[1, 2, 3, 4, 5]
List Contains skipped value :(3, 4, 5)

contains()

Search for specific value in list

Determine whether the provided element is present in the list and return the bool value.

Syntax : listName.contains(value);  

void main() {
  List listName = [1, 2, 3, 4, 5];

print("List Contains value :${listName}");
  print("List check Contains value :${listName.contains(2)}");
}

Your desired OutPut show below :
List Contains value :[1, 2, 3, 4, 5]
List check Contains value :true

Recommended Articles

How to create a Reorderable listview in flutter

Arrays in dart (LIST)

Difference between MVC MVP and MVVM

0
Difference between MVC MVP and MVVM

MVC, MVP & MVVM all this are a project design patterns which are very useful for developer to structure the project & write code that can be easily understandable, maintainable, extensible add need features and tested. All the 3 design pattern share some similarities, and there are difference between MVC MCP & MVVM. In the article post, let’s explore the MVC, MVP & MVVM design patterns. In order to choose the perfect pattern for your upcoming project’s let’s discuss the difference between them.

Model View Controller (MVC)

A Model View Controller (MVC) is a software architectural design pattern mostly used for user Interface (UI design). It separate the project into three parts i.e. Model View Controller, It is a way how to information is presented in front of user or how the data is accepted from user from user event’s.

Model represent a data structure layer of an application (database)

  • the model, which represents the data;
  • the view, which displays the data;
  • the controller, which handles user input.
MVC Design Pattern
MVC Design Pattern

The Model View Controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the way information is presented to or accepted from the user.

Here Controller stores data to the model & tell the view this data is been updated .

View fetch the data/updated data from models and display it in view.

Model View Presenter (MVP)

The Model View Presenter is originated from MVC pattern to fix some short comes of MVC software development architecture.

MVP Design Pattern

Here Presenter role is similar to controller it handles all the input from user and update the view immediately if required. Presenter keep observing the UI events happens in Views, Write/store the data into model, then read back data from model & provide the updated data to View to display it users.

MVP pattern can be used with any type of application, Best to be used in event-driven applications like Rich Internet Application (RIA’s).

Model-View-ViewModel (MVVM architecture)

Recently MVVM is been added into the architecture pattern of software development world. Here View Model Play an important role in the MVVM architecture pattern, It managed the communication between View and Model, This make MVVM application to be built easily and tested then any other pattern.

MVVM Design Pattern
MVVM Design Pattern

MVC, MVP, and MVVM are most commonly used software design architecture patterns. They have their own strength & weaknesses respectively.

Here View knows all about ViewModel, View Model know about model and Model knows nothing.

View Model Perform perform it’s logics and store the data into model, and it also observe the data changes in model immediately update itself for the changed.

MVVM is a more recent addition to the world of software architecture patterns. It builds on MVP by adding a fourth component: the view model. The view model manages communication between the view and the model, providing a clean separation of concerns. This makes MVVM applications easier to develop and test than those using other patterns.

What Application design pattern best for project

MVC, MVP & MVVM each of the has it own advantages & disadvantages and will differ project to project.

I have Personally worked on all three design patterns, MVC & MVP create lots of messy in the architecture.

MVVM design pattern is better then MCV/MVP because MVVM uses unidirectional data & dependencies flow.

Flutter Quill – Text Editor with Text Editing Toolbar

0
Flutter quill package - Text editor toolbar
Flutter quill package - Text editor toolbar

Hi Guy’s Welcome to Proto Coders Point. This Flutter Article on Flutter Quill Package which is a rich text editor and comes with text Editing toolbar.

This Flutter WYSIWYG editor is built for modern mobile platform and it is compatible with web platform also but will under beta version.

How to Implement FlutterQuill in app

First of all you need to install the FlutterQuill (WYSIWYG editor) into your flutter project where you want to implement text editor field with text editing toolbar.

1. Add Dependencies

In Flutter Project, Open pubspec.yaml file and under dependencies add quill package.

dependencies:
  flutter_quill: ^6.1.6

Once added the above package, now hit pub get button on android studio or run flutter pub get in terminal to download the library as external libraries.

2. To us it Import where required

import 'package:flutter_quill/flutter_quill.dart';

How to use FlutterQuill

Video Tutorial

1. Instantiate/Create a Controller

Firstly you need to controller which can control QuillToolbar and QuillEditor widget.

QuillController _controller = QuillController.basic();

In below Code I have attached the QuillController to QuillToolbar and QuillEditor.

2. Create a QuillToolbar

Using Quill toolbar use can customize the text in the text field and give different styling to the texts.

QuillToolbar.basic(
              controller: _controller,
              toolbarIconSize: 25,
              iconTheme: QuillIconTheme(
                borderRadius: 14,
                iconSelectedFillColor: Colors.orange,
              ),
          ),
Flutter Quill Text Editor with Text Editing Toolbar
Customized Quill Toolbar

3. Create a QuillEditor

In QuillEditor widget, user can type his/her text and customize it as per his need.

QuillEditor.basic(
            controller: _controller,
            readOnly: false
 )

Flutter Quill Example – Complete Source Code

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart';
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Quill Example',
      debugShowCheckedModeBanner: false,
      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> {
QuillController _controller = QuillController.basic();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
          QuillToolbar.basic(
              controller: _controller,
              toolbarIconSize: 25,
              iconTheme: QuillIconTheme(
                borderRadius: 14,
                iconSelectedFillColor: Colors.orange,
              ),
          ),
        QuillEditor.basic(
            controller: _controller,
            readOnly: false
        )
      ],
    ));
  }
}

(Solution) node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28′ not found (required by node)

0

You might we facing a issue with NodeJS which is installled on ubuntu OS,

When you run node -v or pm2 list command getting error:- node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28′ not found (required by node).

Solution for GLIBC_2.28 not found (required by node)

I tried various solution from stack overflow from with, Finally One solution worked for me, just by running by below commands.

sudo apt-get remove nodejs
nvm i 16  
sudo apt-get install nodejs
sudo apt-get install npm

node -v

npm -v

nvm -v

Flutter phone number validation regex

0
flutter textfield phone number validation using regex pattern
flutter textfield phone number validation using regex pattern

Are you looking for a phone number validation regex that you can use with or without a country code, brackets, and dash? Well, look no further! In this Flutter Article, I’ll show you how to create a phone number validation regex in flutter that works with any number format.

Whether you’re looking to validate a phone number in the US, Canada, or any other country, This Phone Number regex pattern will help you get the job done quickly and correctly. Plus, it’s simple to use and easy to customize to suit your needs. So be sure to read this article and learn how to implement a phone number validation in flutter TextField using regex that works with any number format!.

I want a regex that matches following phone number pattern string:-

  • XXXXXXXXXX : 10 digit mobile number validation.
  • +91 XXXXXXXXXX : Country code + 10 digit phone number.
  • (XXX) XXX XXXX : Phone number with brackets separator.
  • (XXX) XXX-XXXX : Number with brackets & dash separator.
  • XXX-XXX-XXXX : Phone Number with dash separator.

Here X defines number

International phone number regex

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$

Explanation of above phone number regex

^\s*Starting line , accept white space at beginning.
(?:\+?(\d{1,3}))?Match country code, here ‘?’ makes it optional. remove ‘?’ to validate phone number and make it mandatory.
[-. (]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Area code of 3 digit in phone number string. add ‘?’ at end to make area code optional.
[-. )]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Exchange Number of 3 digit in phone regex string. add ‘?’ at end to make area code optional.
[-. ]*Match special character like dash which may appear between.
(\d{4})Subscriber number of 4 digit in phone number string.
(?: *x(\d+))?Optional Extensional Number.
\s*$Accept any white space at ending of phone number string.
Mobile Phone number Validation Regular expression

Video Tutorial

Flutter Phone Number TextFormField Validation using Regex Pattern

Complete Source code:- main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @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
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  TextEditingController phoneController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
            Form(
              key: _formKey,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextFormField(
                        controller: phoneController,
                        decoration: buildInputDecoration(Icons.phone, "Phone"),
                        keyboardType: TextInputType.phone,
                        onChanged: (value){
                           _formKey.currentState?.validate();
                        },
                        validator: (value){
                          if(value!.isEmpty){
                            return "Please Enter a Phone Number";
                          }else if(!RegExp(r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$').hasMatch(value)){
                            return "Please Enter a Valid Phone Number";
                          }
                        },
                ),
              ),
            )
        ],
      )
    );
  }
}

InputDecoration buildInputDecoration(IconData icons,String hinttext){
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: const BorderSide(
        color: Colors.green,
        width: 1.5
      )
    ),
    border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(25.0),
        borderSide:const  BorderSide(
            color: Colors.blue,
            width: 1.5
        )
    ),
    enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(25.0),
        borderSide:const  BorderSide(
            color: Colors.blue,
            width: 1.5
        )
    ),
  );
}