Home Blog Page 41

How to get difference between two dates in dart for flutter app

0
get difference between two data in flutter
get difference between two data in flutter

Hi Guys, Welcome to Proto Coders Point. In this Flutter/Dart article, will learn how to get time difference between dates, This is very useful when you are building any flutter application & want to substract two dates and get difference between two datetimes in flutter.

To Achieve this we will make use of DateTime.difference method of dart

Example:

void main(){
    final DateTime date1 = DateTime(2022,5,30,11,30,40);

    final DateTime date2= DateTime(2022,5,30,14,30,40);

    final Duration durdef = date2.difference(date1);

    print("${durdef.inHours} Hours");    
    //output (Time difference in Hours): 3 Hours

    print("${durdef.inDays} Days");
    //output (Time difference in days): 0

    print("${durdef.inMinutes} Minutes");
    //output (Time difference in minutes): 180

    print("${durdef.inSeconds} Seconds");
    //output (Time difference in Seconds): 10800

}

Get Time Difference between times

First you need intl package of flutter dart

import 'package:intl/intl.dart';

void main(){
  var format = DateFormat("HH:mm");
var one = format.parse("09:30");
var two = format.parse("13:20");
print("${two.difference(one)} Hours "); // prints 3:50 
}

Flutter datetime difference – App Example:

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

    DateTime date1 = DateTime.parse("2022-05-30 11:47:00");
    DateTime date2 = DateTime.parse("2022-05-31 10:57:00");

    Duration diff = date1.difference(date2);

    return Scaffold(
         appBar: AppBar(
            title: Text("Calculate Difference between DateTime In Flutter App"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[
         
                      Text("First Date :" + date1.toString()),
                      Text("Second Date :" + date2.toString()),

                      Text("Difference in Days: " + diff.inDays.toString()),
                      Text("Difference in Hours: " + diff.inHours.toString()),
                      Text("Difference in Minutes: " + diff.inMinutes.toString()),
                      Text("Difference in Seconds: " + diff.inSeconds.toString()),

                ]
             ),
          )
      );
  }
}

Flutter number round to decimal places

0

Hi Guys, Welcome to Proto Coders Point. This article is all about how to round number to decimal places in flutter/dart.

What do mean by round to decimal places

Check out below image

Flutter round number to decimal places will make use of a in-build method, .toStringAsFixed(2) will help us in getting how much fraction Digits we need after the decimal point and the last number will get round up.

Example

var num = 15.12345;
  print(num.toStringAsFixed(3));      /// 

Here in .toStringAsFixed(3), Here 3 defines the parameter, How many decimal number you want after decimal point.

Example:

void main(){
  
 var n = 15.12345;
  print(n.toStringAsFixed(3));  //  15.123
  
  var x = 4.56;
   print(x.toStringAsFixed(1));  //   4.6
  
    var x1 = 4.53;
   print(x1.toStringAsFixed(1));   //   4.5
  
  var y = -1.55;
   print(y.toStringAsFixed(1));    //   -1.6
  
  var z = 10.5677;
   print(z.toStringAsFixed(3));    //    10.568

 var num = 10.85;
   print(z.toStringAsFixed(0));    //    10
  
}

dart convert double to int

Ternary Operator in dart

why does flutter uses dart language

dart decimal grouping, add commas to number

convert set to list, list to sets in dart

what is spy number in dart

How to round up number in dart language – Flutter

0
Round Up Number in Dart
flutter round double to int

Hi Guys, Welcome to Proto Coders Point. In this flutter dart article let’s learn how to round up a number in Dart Language.

Dart Round Double to Integer

In dart to round up a number to the nearest integer, we can make use of a method round(). This round() method in dart convert double to int. In simple words the decimal point number will get converted to closest integer number.

Eg:

DoubleConverted ToInteger
3.65—>4
2.49—>2

To use dart round() method, we need to import foundation.dart package.

Example: dart convert double to int

import 'package:flutter/foundation.dart';

void main(){
  
 var n = 15.5199;
  print(n.round());      // 16 
  
  var x = 4.49;
   print(x.round());     //  4 
  
  var y = -1.50;
   print(y.round());       // -2 
  
  var z = 0.5;
   print(z.round());      //   1
  
  
  var a = 0.4;
   print(a.round());       //     0
 

}

Learn More on dart official docs.

Ternary operator in flutter dart with Real Example

0
Ternary Operation in flutter dart

Hi Guys, Welcome to Proto Coders Point, This dart/flutter article is on Conditional operator (i.e. Ternary Operation in flutter dart).

Video Tutorial


What is ternary operator with example

In Flutter Dart, We can use Conditional operator in two ways: One is using normal if/else condition statement & another is ternary operator in flutter dart.

Ternary Operator dart takes three operands:

  • A Condition followed by (?) question marks.
  • Then a experssion that execute when condition is true, followed by (:) colon.
  • Then finally a expression that execute when condition is false.

Syntax of Ternary operation in flutter

condition ? if True : if False

Ternary Operation Example

void main(){
  
int num = 10; //init

bool val = (num<=9) ? true : false; // check condition using ternart operations
  
print(val); // return false : as number is > 9
  
}

Nested conditional Operation using Ternary Operation

In dart ternary is right associative, that means it can used to as nested if/else condition like a chains.

Example:

condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : condition4 ? value4
         : condition5 ? value5
         : valueN;

Example: Nested Ternary operation in dart

void main() {
  int age = 30;
  String output = age < 1
      ? 'Infrant is Just Borned'
      : age < 4
          ? 'Baby is less then 4 Year,'
          : age < 12
              ? 'Childhood'
              : age < 18
                  ? 'Adolescence'
                  : 'Grown Up';
  print(output);
}

Example on How to use Ternary Operation in Widget building

An real time example, when and how to use Ternary Conditional Operation to show different widget in flutter depending on condition.

Eg: If Condition is true, show Image Widget else Show Error message using Text Widget.

 bool showImage = true;

Container(
              height: 300,
              width: 300,
              child: showImage ? Image.network('<Image url Here>') : CircularProgressIndicator(),
            ),
bool showImage = false;

Container(
              height: 300,
              width: 300,
              child: showImage ? Image.network('<Image url Here>') : CircularProgressIndicator(),
            ),

How to restart RabbitMQ Server on windows & ubuntu

0
restart rabbitmq server
restart rabbitmq server

Hi Guys, Welcome to Proto Coders Point. In this Article let’s learn how to restart rabbitMQ server on windows and ubuntu.

Before we learn how to start, stop or restart rabbitmq let’s under brief about it:

What is RabbitMQ

Basically in simple words RabbitMQ is a messaging channel (usually called as message broker). RabbitMQ is free to use. It supports Text Streaming Messaging Protocol. RabbitMq uses AMQP (Advanced Message Queuing Protocol). It can also be use with messaging software like MQTT.


How to start, Stop, Restart & reset RabbitMQ server

Windows

Note: Windows -> navigate to RabbitMQ installed Path folder, and then run below commands.

C:\Program Files\RabbitMQ Server\rabbitmq_server-<version>\sbin>


Ubuntu

Just open Terminal and run below command by using prefix sudo

Eg: sudo rabbitmqctl start_app


Start rabbitMQ

To Start the message-broker server, run below command in terminal being into rabbitMQ server sbin folder.

rabbitmqctl start_app

Stop rabbitMQ

To stop rabbit MQ server run below command in terminal

rabbitmqctl stop_app

must of the time, we have stop rabbitMQ server completely when we have to reset MQ config settings.


Reset rabbitMQ config

If you want to make rabbitMQ completely new then just run below command in terminal.

rabbitmqctl reset

OR

rabbitmqctl force_reset

Note: To successfully reset the RabbitMQ server make sure you first stop it.


Restart rabbitmq server

To restart rabbitMQ, make sure you are in RabbitMQ server installed directory in sbin folder.

C:\Program Files\RabbitMQ Server\rabbitmq_server-<version>\sbin>

run terminal as administrator (optional, only if restart failed) and run below command.

rabbitmq-server restart

How to create Flutter SelectableText Widget

0
How to create selectable text in flutter
flutter selectable text

Hi Guys, Welcome to Proto Coders Point, In this flutter Article will learn how to implement a Text Widget that can be selectable,.So to acheive this will make use of flutter selectableText widget, so that a app user can easily select the text, copy it & paste easily.

Usually when we develop any mobile application, The Text with-in the app cannot be selectable to copy(by default),Like how be can perform copy & post operation on website kinds of app.

In this Flutter tutorial lets learn how to make a text selectable in flutter using selectable text widget in flutter app.

Let’s get started

Flutter selectableText

Selectable Text has 2 types of constructor that you can use to give customized styling for TextWidget.

Flutter Single Style Selectable Text Widget (Contructor)

SelectableText(
   String data, 
   {
      Key? key, 
      FocusNode? focusNode, 
      TextStyle? style, 
      StrutStyle? strutStyle, 
      TextAlign? textAlign, 
      TextDirection? textDirection, 
      double? textScaleFactor, 
      bool showCursor = false, 
      bool autofocus = false, 
      ToolbarOptions? toolbarOptions, 
      int? minLines, 
      int? maxLines, 
      double cursorWidth = 2.0, 
      double? cursorHeight, 
      Radius? cursorRadius, 
      Color? cursorColor, 
      selectionHeightStyle = ui.BoxHeightStyle.tight, 
      BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
      DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
      bool enableInteractiveSelection = true, 
      TextSelectionControls? selectionControls, 
      GestureTapCallback? onTap, 
      ScrollPhysics? scrollPhysics, 
      String? semanticsLabel, 
      TextHeightBehavior? textHeightBehavior, 
      TextWidthBasis? textWidthBasis, 
      SelectionChangedCallback? onSelectionChanged
    }
)

Multi-style Selectable Text (constructor)

SelectableText.rich(
   TextSpan textSpan, 
   {
     Key? key, 
     FocusNode? focusNode, 
     TextStyle? style, 
     StrutStyle? strutStyle, 
     TextAlign? textAlign, 
     TextDirection? textDirection, 
     double? textScaleFactor, 
     bool showCursor = false, 
     bool autofocus = false, 
     ToolbarOptions? toolbarOptions, 
     int? minLines, int? maxLines, 
     double cursorWidth = 2.0, 
     double? cursorHeight, 
     Radius? cursorRadius, 
     Color? cursorColor, 
     BoxHeightStyle selectionHeightStyle = ui.BoxHeightStyle.tight, 
     BoxWidthStyle selectionWidthStyle = ui.BoxWidthStyle.tight,  
     DragStartBehavior dragStartBehavior = DragStartBehavior.start, 
     bool enableInteractiveSelection = true, 
     TextSelectionControls? selectionControls, 
     GestureTapCallback? onTap, 
     ScrollPhysics? scrollPhysics, 
     String? semanticsLabel, 
     TextHeightBehavior? textHeightBehavior, 
     TextWidthBasis? textWidthBasis, 
     SelectionChangedCallback? onSelectionChanged
   }
)

Example on How to use Flutter Selectable Text Widget

In below Example, Will implement selectable text, where I will you how to use both SelectableText & SelectableText.rich constructor class, and in below code I have added a textfield so that user can select text and paste it in flutter textField.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Selectable Text Example - ProtoCodersPoint.com')),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: const [
            Text("This is normal text widget, not selectable",style: TextStyle(fontSize: 30),),
            SizedBox(
              height: 20,
            ),
            // SelectableText
            SelectableText(
              'Long Press on me to Copy me, Try it now.',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 20,
            ),
            // SelectableText.rich example 
            SelectableText.rich(TextSpan(
                text: 'The computer was born to solve problems, ',
                style: TextStyle(fontSize: 20),
                children: [
                  TextSpan(
                      text: 'that did not exist before. – ',
                      style: TextStyle(color: Colors.blue)),
                  TextSpan(
                      text: 'Bill Gates',
                      style: TextStyle(color: Colors.red))
                ])),
            SizedBox(
              height: 20,
            ),
            TextField(
              minLines: 3,
              maxLines: 10,
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Paste Copyed Text Here to know is it actually worked'),
            ),
          ],
        ),
      ),
    );
  }
}