Home Blog Page 68

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

The reason why flutter app development is trending in 2021

1
Why Flutter App Development is trending
Why Flutter App Development is trending in 2021

Introduction to Flutter Application Development

A Flutter is a development framework/Kit, created by Google and its team. By using flutter as an app development kit you can develop applications for Android, iOS and Web that too from a single codebase (Code once and build installation setup for the various platforms).

Flutter Dart is an Object-Oriented Programming system concept (oops), which helps in the compilation of code to native code with no additional bridge. Thus it also helps in accelerating the start-up time of an application to a great extent.

Here are some points why flutter app development is trending in 2021

  • Flutter is based on a dart programming language which is the fastest object-oriented programming language and easy to learn.
  • It has a high-performance flutter rendering engine. They are pretty fast in loading widgets and customizable.
  • Due to awesome Widget speed in loading UI, Flutter provides you smooth and easy-to-use feel.
  • Same Business logic and UI design in all Platforms.
  • Flutter reduce code development time/ faster code development
  • The Flutter has its own rendering engine (Google’s Skia).
  • Flutter works almost on any platform.

Why Flutter Mobile App Development? – Pros of Flutter

Google-like company is a flutter backbone.

The main reason why flutter is trending rapidly in 2021 because flutter is been introduced by google, Google Flutter SDK that helps you in building a native application that works for mobile, Web, and also Desktop that too with the help of a single code

Customized Design & Impressive UI Design.

Flutter existing widgets can easily be customized & designed as per your Page UI Design. Flutter app developers can build super awesome app IU with less effort.

 Super Productive

As you know that Flutter comes with the best Feature that is Hot Reload Due to its stateFul development tools. Flutter allows for a very fast iterative coding style.

Perfect for Minimum Viable Product (MVP).

Flutter dart framework that supplies MVP plan that requires limited time such as the project costing will be mininum.

Save lots of time.

As Flutter is a cross platform development framework, code one and distrubute app in several platform, this will save lots of time compaired to native application development.

Flutter Hot reload

Hot Reload feature of Flutter a functionality for instantaneous updates on any change in UI or Dart code, Furthermore. the Hot reload option in flutter allows developer to test the UI loading quickly.

Ready to use the widget.

it has a number of “ready to use” widgets in which most of the widgets help in material design UI concepts.

Community Support & Documentation

The Flutter Community Support is bit small as commpared to react or Ionic application. But Flutter Support is growing very fast now a days.

What is the future scope of Flutter?

I guess that the future scope is to become a successful cross-platform environment flutter for building great mobile apps for iOS, Android.

however, the Flutter community is quite energetic and new packages are added every day to Dart Package and I expect the frequency to grow loads when Flutter 1.0 will be released in all likelihood inside the no longer too far destiny.

Pros of Flutter

Check out how to install flutter

If you are ubuntu user check how to install flutter in ubuntu