Home Blog Page 58

Dart OOPS concepts – object oriented programming

0
dart object oriented programming language
dart object oriented programming language

A dart is a programming language that support all the concepts of object oriented programming such as:

  • Classes
  • Objects
  • Inheritance
  • Polymorphism
  • Interface
  • Abstract class

The main goal of oops concepts in dart is to reduce programming complexity & can execute many tasks at once.

Let’s have a brief introduction of dart oops concepts one by one

1. Classes

Classes are a user defined datatype that describe how an object should behave.

A dart class is a blueprint by which we can create an object to access properties members of a class.

A class in dart can contain:

  • fields.
  • Methods (<gettter>/<setter>).
  • Constructors.
  • User Defined Methods/functions.

Syntax of dart class:

class class_name{
   <field>
  <getter/setter>
  methods or functions
 <constructor.
}

Example below

2. Object

A object is an Instance of a class, so as you know, A Class is a blueprint from which object are created.

A dart object is a logical entity & Physical entity.

Object in dart can be easily understood by taking real-life object such as : Pen, Table, Car, Table etc.

In Dart Object of a class is created by below syntax:

Syntax:

Class_name object_name = Class_name();

Note: In dart there is no need to use new keywork to create a object.

For Easy understanding, class & object in dart let’s take a example of a car.

A Car has a brandName, model_no, color, price, topSpeed, Therefore we have various brands of cars & each car will have a individual properties like name, color and all…

Therefore here each car is an object that is created by using a class.

Dart Class & Object Example – OOPS

Dart Car Program

class Car{

  // data members
  String? brandName;
  String? modelNo;
  String? color;
  int? speed;
  int? price;

   //constructor
   Car(String brandName,String modelNo,String color,int speed,int price){
       this.brandName = brandName;
       this.modelNo = modelNo;
       this.color = color;
       this.speed = speed;
       this.price =price;
   }
}

void main(){
  print("Hello World");

   //creating call object by passing value using parameter constructor
    Car audi = Car('Audi','A6','RED',300,5000000);

    // using object we can access class properties using dot . operator
     print('Name: ${audi.brandName}');
    print('Model No: ${audi.modelNo}');
    print('Car Color: ${audi.color}');
    print('Car Speed: ${audi.speed}');
    print('Car Price ${audi.price}');
}

Dart program to calculate age using data of birth

We will create a class, that will calculate & find the exact age of a person using data of birth.

Here is below dart class & object program, we have 3 properties: datatype, constructor, & a method.

  • dataType: Used to hold the data in variable eg: String webSite = ‘Proto Coders Point‘;
  • constructor: we have parametrized constructor that except 2 parameter (name & date of birth).
  • method: That calculate age using date_of_birth(dob) & print the age on console.

Dart code below:

void main(){
  print("Hello World");
    //create a object by passing value to constructor of class.
    AgeFinderClass myClassObject = AgeFinderClass('Rajat Palankar', DateTime(19XX, X, X));  // pass your dob here : (1999,5,6)

    //calling a method in class using object
    myClassObject.calculate();

}

// dart class 
class AgeFinderClass {
  String name;
  DateTime? date_of_birth;

  // Constructor
  AgeFinderClass(this.name, this.date_of_birth);

  // Method.
  void calculate() {
    print('Name:  $name');
    var date_of_birth = this.date_of_birth;
    if (date_of_birth != null) {
      int years = DateTime.now().difference(date_of_birth).inDays ~/ 365;
      print('Your Age is: $years');
    }
  }
}

3. Inheritance in dart

Inheritance is one of the pillar of object oriented. Inheritance in dart, is very important concepts of OOPS, By using dart Inheritance, we can derive/acquire all the method & behaviour of a parent class.

Eg: Real Life Example

You dad, build house, earn money, has a car, bike & a business, Therefore you have all the rights to use all of his properties.

Inheritance represent the IS-A relationship also been called as parent-child relationship.

Why do we use Inheritance in dart

It’s been used to re-use the method & field of a parent class.

  • Code Reusability
  • Method Overriding (Polymorphism)

Syntax of dart class inheritance

class child-class-name extends parent_class_name{
  
      //method & field

}

Single Inheritance Example

In below example we have 2 class ‘Animal’ & ‘Dog’.

Dog acquire all the properties of Animal class by extending it,

Therefore, now Dog can use Animal class eat() method.

class Animal{
  void eat(){
    print('Eating....');
  }
}

class Dog extends Animal{
  void dark(){
    print('Barking...');
  }
}
void main(){
  Dog d = Dog();  // here d is object of Dog Class
  d.eat();     // dog can use Animal class method
  d.dark();
}

4. Polymorphism in dart

In Dart or any OOPS concept a polymorphism is a feature that perform different action in different situation.

Polymorphism definition says:- A ability of an object to take on many forms, An example of polymorphism is when a parent class refer to child class object.

Real Life example

Let’s take an example to understand polymorphism. A person have many characteristics & perform different roles in his life, He can be a dad, husband, a employee or a business man, so as you saw, The same person plays different roles in different situation. This is the best & easiest way to understand what is polymorphism in dart.

Here poly means many, & morph means forms.

Dart polymorphism example

void main() {
  // parent class object creation
  Animal ma ;
  
  // using parent object, re-initialize subsclass object
  ma =  Dog();
  
  // class method 
  print('Dog making sound: ${ma.makeSound()}');
  
  ma = Cat();
  print("Cat :- "+ma.makeSound());
  
  ma = Bird();
   print("Crow Making sound :- "+ma.makeSound());
}

class Animal{
   makeSound(){
    return "Animal Sound is not Defined";
  }
}


class Dog extends Animal{
  @override
   String makeSound(){
    return "bow wow";
  }
}

class Cat extends Animal{
   //no sound method declared // so it will take sound property from parent class "Animal"
}

class Bird extends Animal{
  @override
  String makeSound(){
    return "AWW! AWW!";
  }

}

In above code, we have a super class i.e Animal which has method makeSound(), Then we have a sub class i.e Dog, Cat, Bird. They have their own sound i.e method implemented to make respective animal sound.

In above code, I have defined sound method for Dog & Bird but not Cat, Therefore when cats makeSound() method is class, it will refer it parent method i.e. superclass Animal & makeSound() “sound is not defined”.

Basic Dart Programs to learn dart

Java OOPS Concepts – easy understanding of oops concepts

Dart enum – How to use enums in dart programming language

0
dart enum
Enumeration in dart

Hi Guys, Welcome to Proto Coders Point. In this Dart Tutorial, we will learn what is enumeration in dart, what does enumeration means & how to use enum in dart programming language & when to use enums.

What is enum in dart

A dart enum is basically a list of named constant values. In dart program enum keyword is used to define enumeration type in dart.

In dart enum is been used to define a collection of constant.

Syntax:

enum enum_name{
  
   constant value 1,   // data member 1
   constant value 2,
   constant value 3,

}

Let’s analysis the above syntax of enum:

  • enum: A enum keyword is used to initialize enumerated data type.
  • enum_name: is a user given name for enum class, is used for naming convension of enumerated class.
  • constant(data member): constant value of enum class & should be seperated by “,” commas.

note: enum class last data member will not have a comma.


When to use enums

As you known enum are list of constants value & is used when you know all the const value at development time.

Where to use enum -> common example suppose you want to a show week days name “MONDAY – SUNDAY” in a dropdown menu at that time you know week days data is constant and will never change.

Enum Dart Code Example Below

Example 1 -> Iterate through enum & print enum class value

enum Fruits{
  mango,
  apple,
  banana,
  grapes
}
void main(){

     for(Fruits name in Fruits.values)
    {
        print(name);
     }
}

Example 2 -> Enum Switch Case Statement

enum Fruits {
  apple,
  mango,
  banana,
  grapes
}
 
void main() { 
   
  // Assign a value from
  // enum to a variable geek
  // assume you app user will select from Menu Item Fruits
  var selectedEnumFruit = Fruits.Banana;
   
  // Switch-case
  switch(selectedEnumFruit) {
    case Fruits.apple: print("You selected Apple");
    break;
    case Fruits.mango: print("You selected mango");
    break;
    case Fruits.banana: print("You selected Banana");
    break;
    case Fruits.grapes: print("You selected Grapes");
    break;
  }
}

Note: The enumeration data is stores a string value without any quatation mark, as normal string data has ” “.


Example 3: Animated Button Loading Indicator using Enum

Check out this article, I created 3 state on a button with animation effect (initial State, Loading, Completed) using Dart enum

Flutter – Loading Spinner on Button click – Circular Progress Button

0
Animated button - loading indicator button

Hi Guys, Welcome to Proto Coders Point, In this flutter article we will implement button in flutter to show a progress or loading indication, useful when a form is been submitted.

  • Loading Spinner Indicator on Button – Flutter:

Useful, when user is submittiing a form & has to wait until form submittion is successful. In that case, we can show a Circular Progress Indicator like showing a loading spinner on a button until form is submitted.

  • Animated Loading Button State – Flutter

Here we will create 3 state of a button Indication.

1. ButtonState.init: initial state of a button (before submitting).

flutter button

2. ButtonState.submitting: A state to indicate user that the form is getting submitting to the server & user need to wait. This state is loading/progress just to show circular Progress.

loading button in flutter

3. ButtonState.completed: A state to indicate that the from is submitted successfuly.

completed button in flutter

Note: This Article source code is just the UI to create a loading button in flutter ( this is not a real time form submission example)


Example 1: Flutter Code – Loading Circular Spinner Button

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

//loading spinner on button
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 70,
          width: MediaQuery.of(context).size.width,
          alignment: Alignment.center,

          child: ElevatedButton(
            style: ElevatedButton.styleFrom(shape: StadiumBorder()),
            onPressed: () async {
              setState(() {
                isLoading = true;
              });
              await Future.delayed(const Duration(seconds: 5));
              setState(() {
                isLoading = false;
              });
            },
            child: (isLoading)
                ? const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 1.5,
                    ))
                : const Text('Submit'),
          ),
        ),
      ),
    );
  }
}

Output of above code

Button Loading Indicator
Button Loading Indicator in flutter

Example 2: Flutter Code – Animated Loading Circular Button State

Code – main.dart

Read the comment in below code for understanding the code flow:

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 ButtonStates(),
    );
  }
}
bool isAnimating = true;

//enum to declare 3 state of button
enum ButtonState { init, submitting, completed }

class ButtonStates extends StatefulWidget {
  const ButtonStates({Key? key}) : super(key: key);

  @override
  _ButtonStatesState createState() => _ButtonStatesState();
}

class _ButtonStatesState extends State<ButtonStates> {
  ButtonState state = ButtonState.init;

  @override
  Widget build(BuildContext context) {
    final buttonWidth = MediaQuery.of(context).size.width;

    // update the UI depending on below variable values
    final isInit = isAnimating || state == ButtonState.init;
    final isDone = state == ButtonState.completed;

    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(40),
        child: AnimatedContainer(
            duration: Duration(milliseconds: 300),
            onEnd: () => setState(() {
                  isAnimating = !isAnimating;
                }),
            width: state == ButtonState.init ? buttonWidth : 70,
            height: 60,
            // If Button State is Submiting or Completed  show 'buttonCircular' widget as below
            child: isInit ? buildButton() : circularContainer(isDone)),
      ),
    );
  }

  // If Button State is init : show Normal submit button
  Widget buildButton() => ElevatedButton(
        style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
        onPressed: () async {
          // here when button is pressed
          // we are changing the state
          // therefore depending on state our button UI changed.
          setState(() {
            state = ButtonState.submitting;
          });

          //await 2 sec // you need to implement your server response here.
          await Future.delayed(Duration(seconds: 2));
          setState(() {
            state = ButtonState.completed;
          });
          await Future.delayed(Duration(seconds: 2));
          setState(() {
            state = ButtonState.init;
          });
        },
        child: const Text('SUBMIT'),
      );

  // this is custom Widget to show rounded container
  // here is state is submitting, we are showing loading indicator on container then.
  // if it completed then showing a Icon.

  Widget circularContainer(bool done) {
    final color = done ? Colors.green : Colors.blue;
    return Container(
      decoration: BoxDecoration(shape: BoxShape.circle, color: color),
      child: Center(
        child: done
            ? const Icon(Icons.done, size: 50, color: Colors.white)
            : const CircularProgressIndicator(
                color: Colors.white,
              ),
      ),
    );
  }
}

Output of above code

Button progress animated loading effect
Button progress animated loading effect

How to Create Multi Step Form – Flutter Stepper Widget

0
flutter stepper widget - multi step form in flutter
flutter stepper widget - multi step form in flutter

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to use flutter Stepper Widget in flutter app to build multi step form, where a user can fill out the information like a progress steppers( step by step form fill ) using Material Stepper in flutter.

Introducation to Flutter Stepper Class

A Stepper Class in flutter is a Material stepper widget that is used to display progress bar a sequence of steps.

Flutter Stepper widget is mostly used where multi step form is needed to be filled & completed in order to reach the final step of submitting the whole form at once to server(Database).

Video Tutorial

Stepper form progress example

Stepper Widget – Snippet Code Implementation

Stepper(
        type: StepperType.horizontal, // or StepperType.vertical
        currentStep: _activeStepIndex,
        steps: stepList(), // pass array list of Step widgets 
        onStepContinue: () {
          // goto next step, simply increment currentStep value by +1
        },
        onStepCancel: () {
        // goto previous step, simply decrement currentStep value by -1

        },
        onStepTapped: (int index) {
          setState(() {
             // directly jump to particular step in stepper
            _activeStepIndex = index;
          });
        },
        controlsBuilder: (context, {onStepContinue, onStepCancel}) {
           // Change UI of
           // next and back button of stepper
        },
      ),

Properties of Stepper Widget Flutter

PropertiesValueDescription
type:StepperType.horizontal
StepperType.vertical
Stepper progress in horizontal or vertical
by default: its Vertical
currectStep:Index value of Step: 0,1,2..Defines the current active step in the form.
onStepContinue()Callback when continue button, to move to next step.
onStepCancel() Callback when cancel button, to move to previous step.
onStepTapped(int index)(int index) Callback when tapped on steps, to move to selected step in progress.
stepsList<Step>The steps of Stepper whose, Title, Content are shown when respective step is Active.
controlsBuilder(context, {onStepContinue, onStepCancel})To change to custom continue(next) & cancel(back) button.
Properties of Stepper Widget Flutter

How to use Stepper Widget in flutter to build a multi step form.

Let’s get Started.

Now, let’s create a Integer value for current Step.

int _activeStepIndex = 0;

We can use this integer value into steps of currentstep whose content is to be displayed.


Now, onStepContinue() is a callback method, called when continue button is pressed.

Here we are checking if _activeStepIndex is less then the number of stepper list if true then increment _activeStepIndex by +1 & apply setState to move to next step.

onStepContinue: () {
          if (_activeStepIndex < (stepList().length - 1)) {
            setState(() {
              _activeStepIndex += 1;
            });
          } else {
            print('Submited');
          }
        }

Therefore when continue button is pressed, will close the current step & move to next step.


Now, onStepCancel() is a callback method, called when user press on ‘cancel’ button.

Here, we will decrement _activeStepIndex by -1,

onStepCancel: () {
          if (_activeStepIndex == 0) {
            return;
          }

          setState(() {
            _activeStepIndex -= 1;
          });
        }

Then when ‘cancel’ button is pressed, will go back to previous step.


Now, onStepTapped(int index), user can press on the step to directly jump to particular step in the form.

onStepTapped: (int index) {
          setState(() {
            _activeStepIndex = index;
          });
        },

Define a list of Step Widgets

Now, Let’s define a List<Step> = [Step(),….] to by shown in stepper widget in flutter.

Will create 3 Steps.

Snippet

List<Step> stepList() => [
    Step(...), //Step 1
    Step(...), //Step 2
    Step(...), //Step 3
  ];

In Step 1: We will ask user about account details, such as Name, Email, Password.

Here, In Step Widget content properties we have defined 3 TextField where a user can enter his account Name, Email, Password.

Step(
          state: _activeStepIndex <= 0 ? StepState.editing : StepState.complete,
          isActive: _activeStepIndex >= 0,
          title: const Text('Account'),
          content: Container(
            child: Column(
              children: [
                TextField(
                  controller: name,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Full Name',
                  ),
                ),
                const SizedBox(
                  height: 8,
                ),
                TextField(
                  controller: email,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Email',
                  ),
                ),
                const SizedBox(
                  height: 8,
                ),
                TextField(
                  controller: pass,
                  obscureText: true,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Password',
                  ),
                ),
              ],
            ),
          ),
        ),

Step 1 – Screenshot

Step 1 in multi step form flutter

In Step 2: We will ask home address of the user.

Here, In Step Widget content properties we have defined 2 TextField to enter address & pincode.

 Step(
            state:
                _activeStepIndex <= 1 ? StepState.editing : StepState.complete,
            isActive: _activeStepIndex >= 1,
            title: const Text('Address'),
            content: Container(
              child: Column(
                children: [
                  const SizedBox(
                    height: 8,
                  ),
                  TextField(
                    controller: address,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Full House Address',
                    ),
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  TextField(
                    controller: pincode,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Pin Code',
                    ),
                  ),
                ],
              ),
            )),

Step 2 – Screenshot

In Step 3: Will be a conformation step, where user can check the information he/she has entered before multi step form is final submission.

Step(
            state: StepState.complete,
            isActive: _activeStepIndex >= 2,
            title: const Text('Confirm'),
            content: Container(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text('Name: ${name.text}'),
                Text('Email: ${email.text}'),
                const Text('Password: *****'),
                Text('Address : ${address.text}'),
                Text('PinCode : ${pincode.text}'),
              ],
            )))

Step 3 – Screenshot



How to customize Stepper Widget Button in flutter

To customize Continue(next) & Cancel(back) button in stepper widget, we have a property called as controlsBuilder.

By Default: We have Continue button and Cancel button to go to next step or go to previous step, you can change it as per your need by using controlsBuilder and add any widget in place of continue & cancel button.

controlsBuilder: (context, {onStepContinue, onStepCancel}) {
          return Container(
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: onStepContinue,
                    child: const Text('Next'),
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                if (_activeStepIndex > 0)
                  Expanded(
                    child: ElevatedButton(
                      onPressed: onStepCancel,
                      child: const Text('Back'),
                    ),
                  )
              ],
            ),
          );
        },

Complete Source Code

How to use Stepper widget to build Multi Step Form in flutter

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> {
  int _activeStepIndex = 0;

  TextEditingController name = TextEditingController();
  TextEditingController email = TextEditingController();
  TextEditingController pass = TextEditingController();
  TextEditingController address = TextEditingController();
  TextEditingController pincode = TextEditingController();

  List<Step> stepList() => [
        Step(
          state: _activeStepIndex <= 0 ? StepState.editing : StepState.complete,
          isActive: _activeStepIndex >= 0,
          title: const Text('Account'),
          content: Container(
            child: Column(
              children: [
                TextField(
                  controller: name,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Full Name',
                  ),
                ),
                const SizedBox(
                  height: 8,
                ),
                TextField(
                  controller: email,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Email',
                  ),
                ),
                const SizedBox(
                  height: 8,
                ),
                TextField(
                  controller: pass,
                  obscureText: true,
                  decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Password',
                  ),
                ),
              ],
            ),
          ),
        ),
        Step(
            state:
                _activeStepIndex <= 1 ? StepState.editing : StepState.complete,
            isActive: _activeStepIndex >= 1,
            title: const Text('Address'),
            content: Container(
              child: Column(
                children: [
                  const SizedBox(
                    height: 8,
                  ),
                  TextField(
                    controller: address,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Full House Address',
                    ),
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  TextField(
                    controller: pincode,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Pin Code',
                    ),
                  ),
                ],
              ),
            )),
        Step(
            state: StepState.complete,
            isActive: _activeStepIndex >= 2,
            title: const Text('Confirm'),
            content: Container(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text('Name: ${name.text}'),
                Text('Email: ${email.text}'),
                const Text('Password: *****'),
                Text('Address : ${address.text}'),
                Text('PinCode : ${pincode.text}'),
              ],
            )))
      ];
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Stepper'),
      ),
      body: Stepper(
        type: StepperType.vertical,
        currentStep: _activeStepIndex,
        steps: stepList(),
        onStepContinue: () {
          if (_activeStepIndex < (stepList().length - 1)) {
            setState(() {
              _activeStepIndex += 1;
            });
          } else {
            print('Submited');
          }
        },
        onStepCancel: () {
          if (_activeStepIndex == 0) {
            return;
          }

          setState(() {
            _activeStepIndex -= 1;
          });
        },
        onStepTapped: (int index) {
          setState(() {
            _activeStepIndex = index;
          });
        },
        controlsBuilder: (context, {onStepContinue, onStepCancel}) {
          final isLastStep = _activeStepIndex == stepList().length - 1;
          return Container(
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: onStepContinue,
                    child: (isLastStep)
                        ? const Text('Submit')
                        : const Text('Next'),
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                if (_activeStepIndex > 0)
                  Expanded(
                    child: ElevatedButton(
                      onPressed: onStepCancel,
                      child: const Text('Back'),
                    ),
                  )
              ],
            ),
          );
        },
      ),
    );
  }
}

Conclusion

Thanks for reading the flutter tutorial article, Here i have explained the basic about flutter stepper widget.

I hope in this flutter programming article, you gained Information on how to use stepper widget.

We learnt, how to change direction of progress stepper (Horizontal/Vertical), & learnt how add multi step form using stepper widget.

Flutter 2.5 – Show Material Banner – Scafford Messenger

0
flutter 2.5 material banner
flutter 2.5 material banner

Hi Guys, Welcome to Proto Coders Point. In flutter 2.5 release, will learn how to make use of flutter Material Banner to show snackbar Flutter Material Banner to app user.

Material you – Material Banner in flutter 2.5 release notes

In Flutter 2.0 release version, they have announced a feature that show a snackbar at the bottom of app screen to notify user about any quick guide information,

ScaffordMessenger Snackbar used to work something that auto dismissable after few seconds, Therefore Snackbar is been used mostly to show a quick message on screen.

So, Now with Flutter 2.5.0 upgrade you can add a Material Banner at top of a screen that will be visible to user until user dismiss it.

flutter material banner ui design
flutter material banner

Video Tutorial


Flutter Upgrade – How to update flutter version

To update your flutter SDK version to 2.5 you just need to run a command on a Command Prompt or IDE Terminal.

flutter upgrade
flutter upgrade 2.5.0
flutter upgrade to 2.5

check flutter version
check flutter version

Now, you can use feature of Flutter 2.5.0


Flutter Material Banner Properties

Snippet code

ScaffoldMessenger.of(context).showMaterialBanner(
        
    MaterialBanner(
        content: const Text('This is Flutter 2.5 Material Banner'),
        leading: const Icon(Icons.info),
        backgroundColor: Colors.yellow,
        actions: [
          TextButton(onPressed: (){}, child: const Text('Some Action')),
          TextButton(onPressed: (){
            ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
          }, child: const Text('Dismiss')),

        ],
      )

    );

Properties to customize Material Banner in flutter

propertiesusage
content:Text Message to be shown to user’s
leading:show a image logo or Icons about the banner information eg: info, warning, success…etc
backgroundColor:Gives color to Material Banner.
actions:[](mandatory) It accept array of widget when user can interact to perform some event.

The Flutter Material Banner according to it’s guidelines, The state of Banner should show only once to the user. If showMaterialBanner is called more then one time, then ScaffordMessenger will maintain a queue for next banner to be shown.

Therefore when previous banner(current active banner) is dismissed then new banner that is in queue will be shown.

removeCurrentMaterialBanner()

As you read above Scafford Messenger showMaterialBanner, maintain a queue of banner, if show MaterialBanner is called more then once, therefore we need to remove the current Material Banner which is active before invoking new Banner.

To do that we just need to call ..removeCurrentMaterialBanner() before invoking new Material Banner in flutter.

    ScaffoldMessenger.of(context)..removeCurrentMaterialBanner()..showMaterialBanner(
        MaterialBanner(
        content: const Text('This is Flutter 2.5 Material Banner'),
        leading: const Icon(Icons.info),
        backgroundColor: Colors.yellow,
        actions: [
          TextButton(onPressed: (){}, child: const Text('Some Action')),
          TextButton(onPressed: (){
            ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
          }, child: const Text('Dismiss')),

        ],
      )
    );

Complete Code – Flutter dart 2.5.0 to show Material Banner (Snackbar) on top

main.dart

Here we have a button ‘Show Banner’ then pressed will call a method that will invoke material banner in flutter.

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(
      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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Material Banner flutter 2.5'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Show Banner'),
          onPressed: (){
            showMaterialBanner();
          },
        ),
      )
    );
  }
  //invoke and display a banner in flutter app
  showMaterialBanner(){
    ScaffoldMessenger.of(context)..removeCurrentMaterialBanner()..showMaterialBanner(
        MaterialBanner(
        content: const Text('This is Flutter 2.5 Material Banner'),
        leading: const Icon(Icons.info),
        backgroundColor: Colors.yellow,
        actions: [
          TextButton(onPressed: (){}, child: const Text('Some Action')),
          TextButton(onPressed: (){
            ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
          }, child: const Text('Dismiss')),

        ],
      )
    );
  }
}

Load HTML, CSS, JavaScript locally in app using Webview Flutter Plus

0
flutter load webpage from assets folder
flutter load webpage from assets folder

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial article will learn How to call html page in flutter locally.

Basically load local web pages such as HTML, CSS, JavaScript from assets folder of flutter project.

So to acheive this we are going to make use of flutter package called ‘webview_flutter_plus‘.

Video Tutorial

About webview flutter plus

Flutter Webview plus is a updated version of webview_flutter.

By using Webview Flutter Plus package we can load local webpage into flutter app like ‘HTML‘, ‘CSS‘, ‘JAVASCRIPT‘ content right from Assets folder of your flutter project.

What’s news in this library

  • It has all the feature present in webview flutter.
  • Load HTML, CSS, JavaScript content from HTML Strings.
  • Load HTML, CSS, JavaScript content from Assets folders.

I have already wrote an Article on flutter_webview, check it out or watch below video

Convert Website into Flutter App


Let’s get Started

Installation

Add this package in pubspec.yaml file

dependencies:
  webview_flutter_plus:

after adding hit ‘put get‘ button or run command flutter pub get, this will add above package library into your flutter project as external Libraries.

Import webview_flutter_plus to use it’s widget

Now once you have added above package, to use it you need to import ‘webview_flutter_plus.dart’ file.

import 'package:webview_flutter_plus/webview_flutter_plus.dart';

Add Internet permission & enable clearTextTraffic

Android

Make sure to add android:usesCleartextTraffic="true", In AndroidManifest.xml, under application tag.

<project-directory> / android / app / src / main / AndroidManifext.xml

<application
     android:label="webview_plus"
     android:icon="@mipmap/ic_launcher"
     android:usesCleartextTraffic="true">
                 .................
                 .................
                 .................
</application>

add Internet permission

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

iOS

Add TransportSecurity & embedded views preview.

<project-directory>/ios/Runner/Info.plist

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key> <true/>
  </dict>
<key>io.flutter.embedded_views_preview</key> <true/> 

Done will basic configuration to load Web pages


How to load Web page in flutter Webview

Snippets Code

1. Loading Website url in flutter app webview

WebViewPlus(
        initialUrl: 'https://protocoderspoint.com/',
        javascriptMode: JavascriptMode.unrestricted,
      ),
flutter webview implementation
flutter webview implementation

2. Load webpage from html string

Way 1 -> Direct load a html string in webview

WebViewPlus(

        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          controller.loadString(r"""
           <html lang="en">
            <body>hello world</body>
           </html>
      """);
        },
      ),

Way 2 -> Create a String variable that hold complete HTML Code

 String htmlpage = ''' <!DOCTYPE html>
<html>
<body>

<h2>Example to load html from string</h2>

<p>This is paragraph 1</p>

<img src="https://thumbs.dreamstime.com/b/sun-rays-mountain-landscape-5721010.jpg" width="250" height="250">

</body>
</html>''';
WebViewPlus(
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          controller.loadString(htmlpage);
        },
      ),

Loading Webpage’s from Assets Folder in flutter app

Let’s create a webpages in Assets & Show it in flutter app using webview_flutter_plus.

Create Assets folder & WebPage Folder in your flutter project

<project_directory>/assets/website

Check my project structure for better understanding

Add permission to access assets folder in pubspec.yaml as shown in above screenshot

flutter:
  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/website/


The Web Page will have radio button when changed will change background color of HTML page.

To Acheive this we need 3 files, so let’s create it under assets/website/....

  1. HTML – > index.html
  2. CSS -> style.css
  3. Javascript -> script.js.

Respective code as below:-

index.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>
<body id="colorback">

<h2>COLOR CHANGE</h2>

<p>Select a Color To Change BackGround</p>

<input type="radio" id="html" name="fav_language" onclick="submit('red')" value="RED" checked>
<label for="html">RED</label><br>
<input type="radio" id="css" name="fav_language" onclick="submit('blue')" value="BLUE">
<label for="css">BLUE</label><br>
<button type="button" onclick="submit('green')" name="Submit">Submit</button>

<script src="scriptpage.js"></script>
</body>
</html>

style.css

#colorback{
        background: red;
        color:white;
}

script.js

function submit(color){
  var colorback = document.getElementById('colorback');

  colorback.setAttribute('style','background:'+color);
}

Flutter – main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WebView Load HTML Locally From assets'),
      ),
      body: WebViewPlus(

        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller){
          controller.loadUrl('assets/website/index.html');
        },
      ),
    );
  }
}

Output – We have a Flutter App that load Webpage from assets folder

Flutter load html page