Home Blog Page 64

Flutter Logger – How to print log messages in flutter.

0
how to log in flutter
flutter logger library

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will cover flutter logger & how to log data in a flutter to help developers in debugging & improving projects for long-term maintenance.

Please note that in this flutter tutorial we will not cover logging in file or logging to remote service.

What is Logger – flutter?

A logger object is used to log/show messages on the IDE console Logcat window.
In Flutter, logging is the most important & useful feature provided that helps developers track, trace, find out the error log & debug logger error.

How to var log message in flutter?

Generally logging messages in flutter can be done using 2 ways

1. Using stdout & stderr


Generally printing a message on the console screen is done using the print() method by importing ‘dart:io’ & by invoking stdout & stderr.

Eg:

         stdout.writeln("This log is using stdout");
         stderr.writeln("This log is using stderr");


Output on Console

Using Print() method Example

print("This Message using Print method");

Suppose, the log message or error log message is long the android just ignores some of the log & print only half of it, In that case you can use ‘debugPrint()’ it will print whole list of log data error.

2. Other is using ‘dart:developer” log() function

This allows developer to include a bit more information in logging output messages.

So to use developer.log function in flutter print to console or devtool, you need to just import ‘dart:developer’ as devlog & now use it as shown below ( devlog.log(“This is Log message from developer log method”); )

import 'dart:developer' as devlog;

void main() {
  
 devlog.log("This is developer log func message",name:'MyLog');
  
}

output: developer.log console log will only be show in devTool

So now you have seen above log method are default dart logs
Here i have found out best flutter logger library that help in printing different kind of logs on console.

Best Flutter Library to log message on console

Flutter Logger Library

Flutter Logger library is very helpful for developer because it help usin printing log message on console n beautiful format.

We all use default log messages to print some statements on the console, as shown above, but they get missed & are difficult to find & might not even see them.

How to use flutter logger library

Learn more obout Logger from Official site

1. Add dependencies

Open pubspec.yaml > under dependenices section add logger: ^1.0.0

dependencies:
  logger: ^1.0.0  #version might change
2. Import the logger dart class

Then to make use of logger flutter you need to import the logger.dart file where you are going to use them.

import 'package:logger/logger.dart';
3. Creating instance of logger class & Printing on the console

default logger instance

  final logger = new Logger();

Custom logger instance

Logger in flutter takes some of the properties that you can customize how your logger message will be displayed on the console screen.

final logger = new Logger(
    printer: PrettyPrinter(
      methodCount: 1,
      lineLength: 50,
      errorMethodCount: 3,
      colors: true,
      printEmojis: true
    ),
  );

Then now once your instance of Logger is been created now you can use the instance object name to print log on console, as shown below

          logger.v("Verbose Log");
          logger.d("Debug Log");
          logger.i("Info Log");
          logger.w("Warning Log");
          logger.e("Error Log");
          logger.wtf("What a terriable failure log");

There are various kinds of log message that you can use to print on the console such as Verbose log, Debug Log, Info Log, Warning Log, Error Log, as shown in the above snippet code.

Outputflutter logger example

Logger Example – flutter

Flutter Null Safety example – handle null exception

0
null safety in flutter
null safety in flutter

Hi Guys, Welcome to Proto Coders Point, so in this flutter tutorial blog article, will learn about flutter null safety with example.

What is null safety in dart?

A Flutter Null Safety feature is a secured way of developing a flutter application, In any programming language, a variable can have a value assigned to it or might be null.

// Eg: Snippet 

String name;  // is null
String firstname = "Rajat Palankar";  //has a value been assigned.

because in dart variable can be null & if a variable is null we cannot perform an action with it like, printing the null value on user screen or we cannot execute at string method to a null value & if we do so this may lead to null pointer exception & your flutter application will crash in run-time.
As shown in below Code and output Screenshot

Example without null safety flutter


#code

// Snippet Flutter Dart code 

class _MyHomePageState extends State<MyHomePage> {
  String name;  // null value
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(name),   // trying to print null # run time , null pointer exception
      )
    );
  }
}

Output example

Here you can see that when i tried to print null in text widget it showing Failed assertion – A non-null string must be provided.

flutter app without null safety

Flutter null safety enable

To solve null pointer exception flutter 2 came with null safety feature.

Set the minimum sdk constrant to 2.12.0 or higher & also check you have updated flutter version(flutter 2)

Then, if you want to use null safety dart then you need to enable null safety to do so, in your flutter project go to

Flutter Project > pubspec.yaml file

change sdk version >= 2.12.0

environment:
  sdk: ">=2.12.0 <3.0.0"   

and run flutter pub get

So now you have successfully enabled null safety in flutter project, now all of our datatype are by default “Not Nullable”

Not nullable means they requires some value to be assigned to them. A String, Int, or any date type must have some value.

Eg: 

int number = 15;

String name = " Proto Coders Point";

What if you want some datatype to be nullable

If in case, you want to make a datatype to be nullable then you need to add a question (?) mark to the datatype.

so in the above example, just by adding ‘?’ immediately after the data type, you can make it nullable which means Null is allowed.

Flutter null Safety Examples

  1. Null Safety Example 1
flutter null safety example
Null safety Example

Late Modifier to achieve null safety

Example without late modifier which gives you null safety error.

String name;   // null safety error
  
  @override
  void initState() {
    super.initState();

    name = "Rajat Palankar";
  }

The above code will give you a null safety compilation error because dart is not clever enough to understand that you have initialized the value to the variable afterwords.

Therefore, to future initialization or late initialization value to variable you can make use of “late modifier”, that tells compiler that value will be initialized later on.

what is late modifier?

In Flutter late keyword will lets you use non-nullable datatype. Now i dart 2.12 has add late modifier, late keyword is used in two case:

  • While migrating flutter project to null safety.
  • Lazy initializing of a variable.

Late keyword is used just to promise dart compiler that you are going to intialize the value to variable later on in future.

Note: if you don’t full fill as promised using late modifier then your flutte app will crash at runtime.

Late modifier example

late String name;  // here I am using late keyword before datatype to tell the compiler that I will initialize the value later

  @override
  void initState() {
    super.initState();

    name = "Rajat Palankar";   // as promised initializing is done here 

    print(name);   //now i can use the variable
  }

Instance Variable in java – with java Program Example

0
instance variable in java with example
instance variable in java with example

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will discuss on what is instance variable java with an example.

Instance Variable java definition

An instance variable is declared in a class just outside the method, constructor, or block of code.

Basically, Java Instance Variable gets instantiated/created when an object of a class is created & destroyed when the object is destroyed. So we all know the class definition: An object is an instance of a class & every object has its own copy of the instance variable.

Point to remember about java instance variable

  1. Instance variable can be accessed only by creating an object.
  2. No need to set the value to an instance variable, by default “0” is set for number, “false” is set for boolean datatype & “null” is for object references.
  3. These are non-static variables.
  4. They are declared inside class just outside method, constructor & block.
  5. using the “new” keyword, when the object is created the class instance variable will also get created & when the object is destroyed even the instance variable gets destroyed.
  6. Initialization of class instance variable java can be done by using class object name as shown below.
Person p1 = new Person();

p1.name = "RAJAT PALANKAR";  //initialization value to variable

Instance Variable Java Example

class Person{
    //instance variable of class
    String name;
    int age;
}


public class Main
{
	public static void main(String[] args) {
	    
		//creating person1 Object
		Person p1 = new Person();
		p1.name="RAJAT PALANKAR";   // initializing value
		p1.age=25;
		
		
		//creating person1 Object
		Person p2 = new Person();
		p2.name="RAM PALANKAR";
		p2.age=25;
		
		//display data of person 2
		
	   System.out.println("Data of person 2");
	   System.out.println(p2.name);
	   System.out.println(p2.age);
	}
}

In above java code, example on instance variable, we have 2 variable in class person i.e. name & age. I have create multiple object by name p1 & p2, each object has it own copies of variable instance values.

output

Data of person 2   
                                                                                                           
RAM PALANKAR                                                                                                                  
25  

Introduction to java programming

Types of variable in java

Best laptop for programming – Android studio requirements 2021

0
Best laptop for programming
best laptop for programming android development

Hi Guys, Welcome to Proto Coders Point, This Blog is about the best laptop for android development to run an android studio on a laptop smoothly.

So, you are planning to buy a new laptop for programming, if yes, then you are in right place, here we will share the best laptop for programming a guide to help you choose the best laptop specification for android studio.

When it comes to android studio development requirements you need to analyze laptop configuration carefully to run android studio smoothly before buying the laptop.
That’s because android studio & Emulator if runs at once it consume lots of RAM & processor load.

Laptop configuration for programming to run Android Studio smoothly

best laptop for android development or flutter development

Here are some specification need to been note before deciding which laptop is best for programming.

1. SSD Storage not HDD:-

I personally suggest you to buy a laptop which had SSD Storage as primary storage where you need to install your Operating System & Programming IDE (like android studio or any other) that will boost loading time of the IDE software, because as per my experience in running android studio on SSD drive is 10X times faster as compaired with HDD.

ssd

SSD Storage is very important & is been ignored by many people while buying new laptop for software development.

My Experience when i switched to SSD : When i used HDD with android studio installed, it took more then 10 minute to load it and even android Emulator used to load very slow almost 10-15 min but now a year back, i switched to SSD & boom now my system boot in just 1 min or less & android stdio loaded completely with build gradle file in just 2 minute or less.

For development with HTML & CSS i.e. web development 4 GB RAM is enought but when it comes to IDE such a android studio which need more RAM memory, 8 GB of RAM is Recommanded for Smooth run android in laptop

Note: if your laptop don’t have SSD then even increasing the RAM to 32 GB, is off no use: so better Buy a laptop that has SSD storage a primary memory.

3. Procesor i5:-

processor

If you are android developer choice a laptop with i5 4th generation or higher, because in low processor like i3, the IDE will run properly but sometime you may face issue such as android studio handing/lagging, build time is more, long time for build to generate apk, Emulator not working or Emulator not responding etc,

I recommended for low budget people, go with atleast i5 4th generation or higher, Best choice is i5 7th generation & higher.

4. Graphic Card:-

graphic card

As such Graphics Card is not that recommended for android development, but if you are a game developer then the graphic is required so better buy a laptop that a graphic card in it.

Graphic card is not required but in graphical view of UI xml design in android studio will boost the view a give a developer a high graphic feeling.

Recommended : Graphic car ( 2gb or higher) (not mandatory)

5 Top best laptop for programming – Android development 2021

1. Apple MacBook Air with Apple M1 Chip

The Apple laptop are best for productivity and apple laptop has longer battery life i.e. 18 hours. The Appe Macbook Air with M1 chip for a giant leap in CPU,GPU and machine learning performance, has upto 8 core CPU that boost performance. Upto to 8 GPU cores gives 5x faster graphics. 16 core Neural Engine that help machine learning developer speed up the execution.

Apple MacBook Air with M1 chip
BrandApple
Operating SystemMacOS 10.14 Mojave
Display13.3-inch(diagonal) LED backlit wiescreen display
ProcessorApple M1 Chip,8-core CPU
Storage256 GB or 512 GB SSD
RAM8GB
Apple Macbook Air Specification

Click here to learn more or buy Apple MacBook Air now


2. Lenovo Ideapad S145

Lenovo Ideapad s145
BrandLenovo
Operating SystemWindows 10
Display15.6 Inch
ProcessorIntel i5 10th generation
StorageHDD : 1 TB & SSD: 256GB
RAM8GB DDR4
Lenovo IdeaPad Specification

Click here to learn more or buy Lenovo IdeaPad S145 now


3. HP Pavilion Gaming  15-ec1052AX

HP Pavilion
BrandHP Pavilion
Operating SystemWindows 10
Display15.6 Inch
ProcessorAMD Ryzen 5 4600H
StorageHDD : 1 TB & SSD: 256GB
RAM8GB DDR4
Graphic CardNVIDIA GeForce GTX 1650, 4 GB
HP Pavilion Gaming Specification

Note: Always install Operating System & any of your Programming IDE(Eg: Android Studio) in SSD drive, so that the loading speed of OS and software will be 10x times faster.

Click here to learn more or buy HP Pavilion laptop now


4. Lenovo Legion 5

The Lenovo Legion 5 is very ultra-light and very slim and portable Gaming laptop, it’s a perfect gaming laptop for Game Lover, and best laptop for android development.

Lenovo legion 5
BrandLenovo, Legion 5
Operating SystemWindows 10
Display15.6 Inch, 1920 x 1080 (Full HD)
ProcessorAMD 4th generation Ryzen 5 4600H
StorageHDD : 1 TB & SSD: 256GB
RAM8GB DDR4
Graphic CardNVIDIA GeForce GTX 1650, 4 GB
Lenovo Legion 5 Specification

Click here to learn more or buy Lenovo Legion 5 now


5. Acer Predator Helios 300 PH315-53-72E9

acer predator helios 300
BrandAcer, Predator Helios 300
Operating SystemWindows 10
Display15.6 Inch, 1920 x 1080 (Full HD)
ProcessorIntel i7 10th Generation
StorageHDD : 1 TB & SSD: 256GB
RAM16GB DDR4
Graphic CardNVIDIA GeForce RTX 2060, 6 GB
Acer Predator Helios Specification

Click here to learn more or buy Acer Predator Helios 300 now


Recommended Post

Coding books for beginners

How to check your Flutter App size using dev tools

0
How to check your Flutter App size using dev tools
How to check your Flutter App size using dev tools

Hi Guys, Welcome to Proto Coders Point, In this article, we will learn about how to check/measure the app size of the flutter apps using dev tools.

Many App developers keep the focus on making their app size as less as possible, App size must be a concern. How much larger an app size, the more space it consumes on a device, if the app size is larger then a longer time is required to download and install on a mobile device.

Why flutter debug build app is large in size

When you use the flutter run or the press play button on your IDE(Android Studio or Visual Studio), it generates a debug build of the flutter app.
The app size of a debug build version is much large/big than the release build version because of debugging overhead that allows us to use flutter features such as hot reload & source-level debugging.
This debugged version of the app is not suitable to be distributed to end-user due to the app size big.

How to analysis app sizes of flutter built

With the Updates on Flutter version 1.22 and DevTools version 0.9.1, an app size analysis tool is been included that help flutter developer in measuring app size and remove unwanted or unused resources from flutter project.

Build apk or IOS file to analyze-size/measuring app size flutter

To invoke app size analysis took you need to pass –analyze-size flag while buildiing app file.

flutter build apk --analyze-size

This will give you “Cannot perform code size analysis when building for multiple ABIs. Specify one of android-arm, android-arm64, or android-x64 in the –target-platform flag“, because you need to pass ABIs

flutter build apk --analyze-size --target-platform android-arm64

different build command for targeted platforms

  • flutter build apk --analyze-size –target-platform *flag
  • flutter build appbundle --analyze-size –target-platform *flag
  • flutter build ios --analyze-size –target-platform *flag
  • flutter build linux --analyze-size –target-platform *flag
  • flutter build macos --analyze-size –target-platform *flag
  • flutter build windows --analyze-size –target-platform *flag

The above terminal command to build is different from standard release.

This build command display a summary describing the md app size in the terminal itself as shown in below screenshot.

flutter build apk --analyze-size

& create a json file by name code_size-analysis_*.json file which contain more detail analyze of app, you can analyze the app size in dev too by uploading the json file code_size-analysis_*.json.

Deeper analyze/measuring app size using devtools

However the summary related to app size in terminal is not a perfect details of app build, it can be just a quick idea of size of resources category such as assets, native code, external library used & much more.

So when you use above command to build app, it generate a json file that can be used in analysing deeper using dev tools.

Where JSON tree map can break down the content of app into individual file.

How to open Dev Tools in android studio.

Time needed: 2 minutes.

Steps to open Flutter Dev Tools in android Studio

  1. In IDE – Go to Terminal

    To Open Terminal in android Studio go to Toolbar > View > ToolWindows > Terminal
    or just press Alt + F12.

    terminal in android studio

  2. Command to open DevTools in android studio

    flutter pub global run devtools

    This will open devtools window/ Local website URL.
    lutter pub global run devtools

  3. Now upload the app size json file in dev tool

    now just upload the JSON file (C:\Users\PCName.flutter-devtools\apk-code-size-analysis_01.json) of the app that you want to analyze app size.

    flutter app analyze size dev tools

  4. Result of measuring app size


     dev tool detail measuring app size

Text animation in flutter – Animated Text Kit package library

0
text animation
text animation

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will implement text animation in flutter by using animated text kit flutter package/library.

Introduction to Flutter Animated_Text_Kit package

A Flutter package that contains lots of awesome & cool text animation effects in a flutter, This Animated text package contain animation properties like text rotate animation, fade in fade out animation, flutter animated typing text, scale animation effect, Colorize, TextLiquidFill, Wavy, and much more animation effect is been added in this flutter package.

Official Package site

So Let’s Begin Adding this Library in our flutter Project

Video Tutorial

Installation of Animated_Text_Kit package

  1. Create a new Flutter
    Of course, you need to create a new Flutter project or open an existing flutter project where you want to add text anim effect. In my case i am using android studio flutter to implement the same.

  2. Add Dependencies

    To add this library to your project just open pubspec.yaml file

and then under dependencies section add it

dependencies:
  animated_text_kit: ^4.1.0

3. Import the animated_text_kit.dart file

Now once you have added the dependencies now you can use the animated text package just by importing the dart file anywhere in your flutter app code.

import 'package:animated_text_kit/animated_text_kit.dart';

Syntax – How to use AnimatedTextKit in flutter

 AnimatedTextKit(
            animatedTexts: [
              TypewriterAnimatedText(
                'Hello world!',
                textStyle: const TextStyle(
                  fontSize: 32.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
               totalRepeatCount: 4,
               pause: const Duration(milliseconds: 1000),
               displayFullTextOnTap: true,
               stopPauseOnTap: true,
          ),
Flutter animated typing text

Here in above snippet code, the text animation by default repeats for 3 times only, and with each loop of animation effect will pause for 1 second and repeat the anim again. if you want to repeat animation just add a property totalRepeatCount: #number as done in above snippet.

Customize the animation effect on text – Properties of this Library

  • pause – The time gap between the next animation texts effect.
  • displayFullTextOnTap – Then user tap on the animation text with will display the full text.
  • isRepeatingAnimation – controls whether the animation repeats
  • repeatForever – set to true if you want the animation to repeat forever until the user is on the screen.
  • totalRepeatCount – By Default repeat count is 3, to change it just set a repeat count number of times the animation should repeat (when repeatForever is false)

There are also custom callbacks:

  • onTap – Event to be performed then animation text is pressed.
  • onNext(int index, bool isLast) – This is called before the next text animation, after the previous one’s pause
  • onNextBeforePause(int index, bool isLast) – This is called before the next text animation, before the previous one’s pause
  • onFinished – This is called at the end, when the parameter isRepeatingAnimation is set to false

Combine multiple animation in one

AnimatedTextKit(
              animatedTexts: [
                FadeAnimatedText(
                  'Fade First',
                  textStyle: TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),
                ),
                ScaleAnimatedText(
                  'Then Scale',
                  textStyle: TextStyle(fontSize: 70.0),
                ),
              ],
              repeatForever: true,
       ),

Here in above snippet you see animatedTexts is a list widgets where we can pass more then one widget, it will work step by step means the first widget will run first then the next then the next and so on until the end.

Multiple Animation text in one

Other text animation effect in this flutter package

RotateAnimationText

Row(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    const SizedBox(width: 20.0, height: 100.0),
    const Text(
      'Be',
      style: TextStyle(fontSize: 43.0),
    ),
    const SizedBox(width: 20.0, height: 100.0),
    DefaultTextStyle(
      style: const TextStyle(
        fontSize: 40.0,
        fontFamily: 'Horizon',
      ),
      child: AnimatedTextKit(
        animatedTexts: [
          RotateAnimatedText('AWESOME'),
          RotateAnimatedText('OPTIMISTIC'),
          RotateAnimatedText('DIFFERENT'),
        ]
        onTap: () {
          print("Tap Event");
        },
      ),
    ),
  ],
);

FadeAnimatedText

Center(
        child: SizedBox(
          width: 250.0,
          child: DefaultTextStyle(
            style: const TextStyle(
              fontSize: 32.0,
              fontWeight: FontWeight.bold,
            ),
            child: AnimatedTextKit(
              animatedTexts: [
                FadeAnimatedText('Its'),
                FadeAnimatedText('Its Awesome...'),
                FadeAnimatedText('Its Awesome Animation'),
              ],
              onTap: () {
                print("Tap Event");
              },
            ),
          ),
        ),
      ),
fadeanimatedtext

TyperAnimationText

 Center(
        child: SizedBox(
          width: 250.0,
          child: DefaultTextStyle(
            style: const TextStyle(
              fontSize: 30.0,
              fontFamily: 'Bobbers',
            ),
            child: AnimatedTextKit(
                animatedTexts: [
                  TyperAnimatedText('A programming language is for thinking about programs, '
                      'not for expressing programs you’ve already thought of. '
                      'It should be a pencil, not a pen....'),

                ]

          ),
        ),
      ),
      ),

For more Animation Effect visit official package site here

Recommended Flutter Post

Flutter Animation – Custom Animation effect

Flutter Rich Text Widget Example