Home Blog Page 64

Dart program to generate fibonacci sequence number

0
fibonacci program in dart

Hi, Welcome to Proto Coders Point, In this dart programming tutorial we will learn what is fibonacci number & write a dart program to generate fibonacci sequence number from 0 – N. It is one of the basic program every programming should know it.

What is fibonacci sequence number?

In mathematic, the fibonacci series, is denoted by Fn.
Here, the next number will be the sum of previous two numbers.

Initial starting two numbers will be 0 & 1, denoted by F0 = 0, F1 = 1;

Simple mathematical formula to get Fn ‘ the next number’..

Fn = F(n-1) +F(n-2)

Therefore, the fib sequence looks like this:-

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ and so on up to Nth

How is fibonacci numbers generated?

Initially we have starting number which always start with 0 & 1 i.e F0 = 0, F1 = 1;

Now we perform sum of F0 + F1 = Fn.

i.e. F2 = F0 + F1.

Fibonacci Sequence flow animation example

Eg: initial value 0 & 1.

1st iteration: F2= F0 + F1
0 + 1
F2 = 1

2nd iteration: F3= F1 + F2
1 + 1
F3 = 2

3rd iteration: F4= F2 + F3
1 + 2
F4 = 3

4th iteration: F5= F3 + F4
2 + 3
F5 = 5

5th iteration: F6= F4 + F5
3 + 5
F6 = 8

and so on up to Nth

How to implement fibonacci in dart? Fibonacci Algorithm.

Step1: Start
Step2: Declare initial variable f0 = 0, f1 = 1,f2, n, i =1;
Step3: Read n from user, how many fibo sequence user wants to generate.
Step4: Print f0 & f1
Step5: Repeat until i < n
5.1: f2 = f0 + f1;
5.2: Print f2;
5.3: inter change value f0 = f1;
f1 = f2;
5.4: i ++;
Step6: Stop.

Fibonacci program using dart

Fibonacci program using loop

void main() {
  int n1=0,n2=1,n3;
  print(n1);
  print(n2);
  
  for(int i = 2 ;i <= 16; i++){
   n3 = n1+n2;
    print('$n3');
    n1 = n2;
    n2 = n3;
  }
}

Fibonacci program using recursion

int fibonacci(int n) => n <= 2 ? 1 : fibonacci(n - 2) + fibonacci (n - 1);

main() {
  String output = "";
  for (int i = 1; i <= 16; ++i) {
    output += fibonacci(i).toString() + ", ";
  }
  print(output + "...");
}

output

What is a real world example of the Fibonacci numbers?

One of the best & easiliest way to understand fibonacci series used in real file application is, converting mile to kilometer and kilometer to mile.

Let’s now see the Fibonacci series :

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,…

For example :

  1. Mile to kilometer conversion : If we take a number from Fibonacci series i.e., 8 then the kilometer value will be 12.874752 by formulae, which is nearly 13 by rounding.
  2. Kilometer to mile conversion : If we take a number from Fibonacci series i.e., 89 as kilometer value then mile value will be 55.30203610912272 by formulae, which could be considered as 55 by rounding.

Finally in both conversions, the left element will be considered as mile value and right element will be considered as Kilometer value in the Fibonacci series.

Implement dotted border or dashed border around widgets in flutter

0
flutter dotted border

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial(Article) we will learn how to give dotted border around any widget in flutter.

Note: to add dashed border or dotted border to our widget, we will make use of flutter_dotted_border package. that let’s developer to easilt implement dotted border in flutter.

Output example

dotted border example
dotted border example

Video Tutorial

Installation of package

1. Run a command to install the package

flutter pub add dotted_border

In your IDE terminal type above command & enter. It will add line in pubspec.yaml file.

dependencies:
  dotted_border: ^2.0.0  #latest version

OR

Directly add it under dependencies section

Open pubspec.yaml file and under dependencies section add the border dotted library.

dependencies:
  dotted_border: ^2.0.0  #latest version

2. Import dotted_border.dart file

once you have added the package now you just need to import it wherever required.

import 'package:dotted_border/dotted_border.dart';

How to use usage

you just need towrapany of your widget where i want to give a border with DottedBorder widget.

Example: Snippet code

DottedBorder(
        child: FlutterLogo(
          size: 148,
        ),
  ),

Here in above snippet, I have a flutterLogo widget for which i want a border, so i have just wrapped it as above.

BorderType

giving bordershape and radius to it.

Rect

DottedBorder(
        child: FlutterLogo(
          size: 148,
        ),
        borderType: BorderType.Rect,
        dashPattern: [10,5,10,5,10,5], //optional
      ),
flutter rectangle border

RRect BorderRadius

DottedBorder(
        child: FlutterLogo(
          size: 148,
        ),
        borderType: BorderType.RRect,
        radius: Radius.circular(20),
        dashPattern: [10,5,10,5,10,5],
      ),
flutter  rounder rectangle border

Circle Border and oval Border

flutter circle border
DottedBorder(
        child: FlutterLogo(
          size: 148,
        ),
        borderType: BorderType.Circle,
         dashPattern: [10,5,10,5,10,5],
      ),
DottedBorder(
          child: ClipOval(
              child: FlutterLogo(
            size: 148,
          )),
          borderType: BorderType.Oval,
          dashPattern: [10,5,10,5,10,5],
),
flutter clipoval example border

#image

Dash Pattern

Then, if you want to customize the space between dash border, you can easily do it by property ‘dashPattern’ just specity the dash sequence by passing array list of pixel size of dash size & empty space.

DottedBorder(
        dashPattern: [10,5,10,5,10,5], 
        child: FlutterLogo(
            size: 148,
          ),
    )

The above dash Pattern will build dash border in a sequence

Eg: 10 pixel wide dash.
5 pixel wide space.
10 pixel wide dash and so on until complete border is completed.

Custom painting dotted path border

let’s draw a star pattern in flutter

first create a custom paint path.

Path customPath = Path()
    ..moveTo(20, 20)
    ..lineTo(50, 80)
    ..lineTo(80, 18)
    ..lineTo(18, 55)
    ..lineTo(82, 55)
    ..lineTo(20, 20)
  ;

Now apply the line drawing path to dotted widget

DottedBorder(
            customPath: (size) => customPath, // PathBuilder
            color: Colors.blue.shade800,
            strokeCap: StrokeCap.round,
            dashPattern: [3, 3],
            strokeWidth: 2,
            child: Container(
              height: 120,
              width: 120,

            ),
          ),
star pattern drawing

Complete source code – flutter dotted border example

main.dart

In below code.

I am use GridView to build list of widget with dotted border.

firstly i have initialized 2 array list of type BorderType & and double list. In BorderType we have type such as RRect for show rounded rectangle, Rect to get simple rectangle border, circle to show fully rounded border and Oval to show oval shape in border.

Then this list is been passed through itemBuilder to create widget BuildBorderWidget.

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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 {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 // create a list of bordertype so 
  List<BorderType> borderTypeList = [
    BorderType.RRect,
    BorderType.Circle,
    BorderType.Rect,
    BorderType.Oval
  ];
  List<double> radiusnumber = [20, 0, 20, 0];

  Path customPath = Path()
    ..moveTo(20, 20)
    ..lineTo(50, 80)
    ..lineTo(80, 18)
    ..lineTo(18, 55)
    ..lineTo(82, 55)
    ..lineTo(20, 20)
  ;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GridView.builder(
                  shrinkWrap: true,
                  physics: ScrollPhysics(),
                  itemCount: borderTypeList.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, crossAxisSpacing: 4.0, mainAxisSpacing: 4),
                  itemBuilder: (BuildContext context, int index) {
                    return BuildBorderWidget(
                        borderTypeList[index], radiusnumber[index]);   // call custom widget to build it.
                  }
         ),

         // draws star shape pattern
          DottedBorder(
            customPath: (size) => customPath, // PathBuilder
            color: Colors.blue.shade800,
            strokeCap: StrokeCap.round,
            dashPattern: [3, 3],
            strokeWidth: 2,
            child: Container(
              height: 120,
              width: 120,

            ),
          ),
            ],
          ),
        ),
      ),
    );
  }
}

// this custom widget is been called from GridView.builder
Widget BuildBorderWidget(BorderType borderType, double radius) {
  return Center(
      child: DottedBorder(
        dashPattern: [10,5,10,5,10,5],
        child: borderType == BorderType.Oval ? ClipOval(
        child: FlutterLogo(
        size: 148,
      ),
    ) : FlutterLogo(
      size: 148,
    ),
    borderType: borderType,
    radius: Radius.circular(radius),
  ));
}

Output

Failed to load network image [Solved 100%]

0
Failed to Load Network image flutter web
Failed to Load Network image flutter web

Hi Guys, Welcome to Proto Coders Point. I was working with one of my flutter project, the app is working perfectly in android & iOS mobile but when i run the flutter web project in browser. The Image i want to load from Network is not loading and in console it’s showing the error “Failed to load network image” flutter web.

ClipOval(
      child: Image.network('https://protocoderspoint.com/wp-content/uploads/2019/10/mypic-300x300.jpg',fit: BoxFit.cover,)),
   ),
======== Exception caught by image resource service ================================================
 The following ImageCodecException was thrown resolving an image codec:
 Failed to load network image.
 Image URL: https://protocoderspoint.com/wp-content/uploads/2019/10/mypic-300x300.jpg
 Trying to load an image from another domain? Find answers at:

Solution “Failed to load network image”

Flutter user two type of renderer for web app, canvakit & html.

when you run/build app on flutter web it uses renderer based on the device the app is run.

  • Flutter HTML renderer: when app it run on mobile devices.
  • Flutter Canvakit renderer: when the app is run on desktop browser – flutter web.

The HTML renderer can load cross-origin image, there is not need to add any extra configuration.

Run below command to solve ‘failed to load Network image’ in flutter web

so use below command to run/build

run for debugging

flutter run -d chrome --web-renderer html

production release

flutter build web --web-renderer html --release

Flutter Web – Drag and drop to upload files – Drop files in Flutter Dropzone

0
flutter web dropzone
flutter web dropzone

Hi Guys, Welcome to Proto Coder Point. In this flutter tutorial article, we will learn a simplest way to implement drag & drop feature in flutter web, By using which, a user can easily drop to upload a file such as images, video, document etc in to flutter dropzone.

Note: To add drop & dropzone in our flutter web app we will make use of ‘flutter_dropzone‘ package.

Video Tutorial

Complete Code is Below & Output 👇👇👇👇

Introduction to flutter dropzone package

A dropzone in flutter is a plugin, flutter for web only, by using which a developer can easily add drag & drop zone feature in flutter app.

A user can easily make use of this feature to drop a file or pickFile from brower file picker window.

Important Note: This package is only for flutter web app. As you all know that drop drop can’t be done in mobile devices.

So let’s quickly start adding this package in our flutter project.

Implementing Flutter drag and drop in flutter web app

1. Create or Open a flutter project

Onen your favorite IDE, My favorite IDE is Android-Studio to build flutter application.

goto > File > New > New Flutter Project ( Give good name to project > Next & Done)

your project will get created.

To open existing flutter project

goto > File > open ( select the project and open )

2. Add flutter_dropzone dependenies

Now, open pubspec.yaml file & under dependencies section add dropzone package.

dependencies:
  flutter_dropzone: ^2.0.1

3. Import flutter_dropzone.dart

Then, once you have added the dependencies in your project as a external libraries, to use it you need to import wherever you want to add dropzone.

import 'package:flutter_dropzone/flutter_dropzone.dart';

4. Syntax & properties of DropzoneView Widget

DropzoneView(
                onCreated: (controller) => this.controller = controller,
                onDrop: UploadedFile,
                onHover:() => setState(()=> highlight = true),
                onLeave: ()=> setState(()=>highlight = false),
                onLoaded: ()=> print('Zone Loaded'),
                onError: (err)=> print('run when error found : $err'),
            ),

properties of dropzoneview

Methodused for
onCreated:(controller)Attach a DropzoneController so that you ca control it & get data/information from event the user perform.
onDrop: (event)Whe user drop a file this function will hold all the data of file such as name, size, mime, URL path of file.
OnHover: ()(Not Mouse Hover) This Function will work when user hover a file on dropping zone in flutter web app.
OnLeave: ()Load when user is hover on dropzon and drop the file and leave it.
OnError: (error)Handle error such a error in file reading by browser
OnLoaded: ()Load as soon as widget is build in UI.

How to make full UI Screen as Drag n drop

To make complete UI screen of flutter web app as dropzone, so that user can simply drag n drop anywhere into your UI, then make use of Stack widget.

Use a Stack Widget to put it into the background of other widget.

Stack( 
  children: [  
   DropzoneView(...),
     Center(child: Text('Drop files here')), 
  ], 
)

DropzoneViewController

This library has a file picking functionality, controller should be used to pick a file from browser, when a choose file button is clicked.

late DropzoneViewController controller;

pickFiles() method simply load & open, choose file dialog window in your browser that lets users to pick file.

final events = await controller.pickFiles();

snippet of button event that loads pickFile() method.

ElevatedButton.icon(
    onPressed: () async {
              // this will open a diglog in browser to pick a file..
               final events = await controller.pickFiles();
               if(events.isEmpty) return;
             // the user selected file detail is stored in event dynamic datatype and passed through method.
               UploadedFile(events.first);
    },
    icon: Icon(Icons.search),
    label: Text(
               'Choose File',
               style: TextStyle(color: Colors.white, fontSize: 15),
    ),
style: ElevatedButton.styleFrom(
          padding: EdgeInsets.symmetric(
          horizontal: 20
  ),
  primary: highlight? Colors.blue: Colors.green.shade300,
  shape: RoundedRectangleBorder()
),
)

Now all the data detail of pickedFile is stored in ‘events’ object, so to extract picked File information dropzoneViewController object is used, as shown below.

final name = event.name;
final mime = await controller.getFileMIME(event);
final byte = await controller.getFileSize(event);
final url = await controller.createFileUrl(event);


Complete source code of flutter drag and drop Github

Clone the Flutter Web Drag and Drop Example from Github now

you can simple clone the project or else refer below step by step process to implement drag drop area in flutter web.

Check out my flutter project files structure for easy understanding.

In your Project > lib folder

create a new dart class file for handling Data by name file data model.

1. File_Data_Model.dart

class File_Data_Model{
  final String name;
  final String mime;
  final int bytes;
  final String url;

  File_Data_Model({required this.name,required this.mime,required this.bytes, required this.url});

  String get size{
    final kb = bytes / 1024;
    final mb = kb / 1024;

    return mb > 1 ? '${mb.toStringAsFixed(2)} MB' : '${kb.toStringAsFixed(2)} KB';
  }

}

This data model class is used to hold the data of the file dropped or picked by the user.
This file holds 4 datatype value such as name of file, mime type of file, int byte size of file and the URL path of the selected file.

It also has a getter method that convert bytes to MB or KB & return the size of file to user UI.


main.dart

import 'package:drag_drop_example/DropZoneWidget.dart';
import 'package:drag_drop_example/DroppedFileWidget.dart';
import 'package:drag_drop_example/model/file_DataModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dropzone/flutter_dropzone.dart';

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

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

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

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {
  //object of datamodel class
  File_Data_Model? file;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("drag drop flutter Web"),
      ),
      body: SingleChildScrollView(
        child: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(15),
            child: Column(
              children: [
                // here DropZoneWidget is statefull widget file
                Container(
                  height: 300,
                  child: DropZoneWidget(
                    onDroppedFile: (file) => setState(()=> this.file = file) ,
                  ),
                ),
                SizedBox(height: 20,),
                // DroppedFileWidget is self designed stateless widget to displayed user dropped image file as preview with detail info
                DroppedFileWidget(file:file ),

              ],
            )),
      ),
    );
  }
}

In above code, we have a Column widget which has 3 children widget.


DropZoneWidget.dart

Now Create a new dart file by name DropZoneWidget.dart in lib directory as shown in above project structure.

import 'package:drag_drop_example/model/file_DataModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dropzone/flutter_dropzone.dart';
import 'package:dotted_border/dotted_border.dart';

class DropZoneWidget extends StatefulWidget {

  final ValueChanged<File_Data_Model> onDroppedFile;

  const DropZoneWidget({Key? key,required this.onDroppedFile}):super(key: key);
  @override
  _DropZoneWidgetState createState() => _DropZoneWidgetState();
}

class _DropZoneWidgetState extends State<DropZoneWidget> {
  //controller to hold data of file dropped by user
  late DropzoneViewController controller;
  // a variable just to update UI color when user hover or leave the drop zone
  bool highlight = false;

  @override
  Widget build(BuildContext context) {

    return buildDecoration(
       
        child: Stack(
          children: [
            // dropzone area 
            DropzoneView(
                // attach an configure the controller
                onCreated: (controller) => this.controller = controller,
                // call UploadedFile method when user drop the file
                onDrop: UploadedFile,
                // change UI when user hover file on dropzone
                onHover:() => setState(()=> highlight = true),
                onLeave: ()=> setState(()=>highlight = false),
                onLoaded: ()=> print('Zone Loaded'),
                onError: (err)=> print('run when error found : $err'),
            ),

            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.cloud_upload_outlined,
                    size: 80,
                    color: Colors.white,
                  ),
                  Text(
                    'Drop Files Here',
                    style: TextStyle(color: Colors.white, fontSize: 24),
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  // a button to pickfile from computer
                  ElevatedButton.icon(
                      onPressed: () async {
                        final events = await controller.pickFiles();
                        if(events.isEmpty) return;
                        UploadedFile(events.first);
                      },
                      icon: Icon(Icons.search),
                      label: Text(
                        'Choose File',
                        style: TextStyle(color: Colors.white, fontSize: 15),
                      ),
                  style: ElevatedButton.styleFrom(
                    padding: EdgeInsets.symmetric(
                      horizontal: 20
                    ),
                    primary: highlight? Colors.blue: Colors.green.shade300,
                    shape: RoundedRectangleBorder()
                  ),
                  )
                ],
              ),
            ),
          ],
        ));
  }

  Future UploadedFile(dynamic event) async {
    // this method is called when user drop the file in drop area in flutter
    
    final name = event.name;
    final mime = await controller.getFileMIME(event);
    final byte = await controller.getFileSize(event);
    final url = await controller.createFileUrl(event);

    print('Name : $name');
    print('Mime: $mime');

    print('Size : ${byte / (1024 * 1024)}');
    print('URL: $url');
    
     // update the data model with recent file uploaded
    final droppedFile = File_Data_Model
      (name: name, mime: mime, bytes: byte, url: url);

    //Update the UI
    widget.onDroppedFile(droppedFile);
    setState(() {
      highlight = false;
    });
  }

  Widget buildDecoration({required Widget child}){
    final colorBackground =  highlight? Colors.blue: Colors.green;
    return ClipRRect(
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: EdgeInsets.all(10),
        child: DottedBorder(
          borderType: BorderType.RRect,
            color: Colors.white,
            strokeWidth: 3,
            dashPattern: [8,4],
            radius: Radius.circular(10),
            padding: EdgeInsets.zero,
            child: child
        ),
        color: colorBackground,
      ),
    );
  }
}

DroppedFileWidget.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:drag_drop_example/model/file_DataModel.dart';

class DroppedFileWidget extends StatelessWidget {

  // here we get the uploaded file data
  final File_Data_Model? file;
  const DroppedFileWidget({Key? key, required this.file}) : super(key: key);

  @override
  Widget build(BuildContext context) {

  return Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Expanded(child: buildImage(context)),
    ],
  );
  }

  // a custom widget to show image
  Widget buildImage(BuildContext context){
    // will show no file selected when app is open for first time.
    if (file == null) return buildEmptyFile('No Selected File');
    
    return Column(
      children: [
        if(file != null) buildFileDetail(file),
        // if file dropped is Image then display image from data model URL variable
        Image.network(file!.url,
          width: MediaQuery.of(context).size.width ,
          height: MediaQuery.of(context).size.height,
          fit: BoxFit.cover,
          // if displaying image failed, that means there is not preview so display no preview
          errorBuilder:(context,error,_)=>buildEmptyFile('No Preview'),
        ),
      ],
    );
  }

  //custom widget to show no file selected yet
  Widget buildEmptyFile(String text){
     return Container(
       width: 120,
       height: 120,
       color: Colors.blue.shade300,
       child: Center(child: Text(text)),
     );
  }

  
  //a custom widget to show uploaded file details to user
  
  Widget buildFileDetail(File_Data_Model? file) {
    final style = TextStyle( fontSize: 20);
    return Container(
       margin: EdgeInsets.only(left: 24),
       child: Column(
         mainAxisAlignment: MainAxisAlignment.start,
         children: [
           Text('Selected File Preview ',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 20),),
           Text('Name: ${file?.name}',style: TextStyle(fontWeight: FontWeight.w800,fontSize: 22),),
           const SizedBox(height: 10,),
           Text('Type: ${file?.mime}',style: style),
           const SizedBox(height: 10,),
           Text('Size: ${file?.size}',style: style),
           SizedBox(height: 20,)
         ],
       ),
    );
  }
}

Output

Flutter Switch – Keep it on/off even when user close app & re-visit

0
flutter switch
flutter switch

Hi Guys, Welcome to Proto Coders Point. In this flutter article we will learn about flutter switch button & how to keep it on/off when user close the app, re-visit the app & switch button will be in same state as it was before user leave the app.

Note: To achieve this we will make use of 2 packages.

  1. Get: Also called as flutter GetX package, we will use it for Getx State Management in flutter.
  2. GetStorage: To store data of user action in app memory. GetStorage is alternative of SharedPreferences.

Video Tutorials on Flutter Switch with Getx

Flutter switch – using default state management – using setState()


Flutter switch button example – by using GetX State Management

Check out both the video to implement in your project while watching video.


Add dependencies get & getstorage

In your flutter project open pubspec.yaml then under dependencies add it.

dependencies:
  
  get: ^4.1.4
  get_storage: ^2.0.2

Get: Also called as GetX, used for many operation such as route management, state management, navigating pages, email validation, GetXStorage, show snackbar, show alert dialog and more.
In our project we will just use getx state management to update the widget state without refreshing complete widget tree just to update 1 widget.

GetStorage: A Flutter GetXStoarge is an alternative of sharedPreferences which help you to store app data in memery that a user perform.
In our project we will store weather the user has turned ON switch or OFF switch before leaving the app, and when he return to app the switch button in flutter will be in same state as it was before user leave the app.

Note: To use getstorage u must also add getX dependencies else getStorage will return you error.

Complete source code below

Flutter Switch example – using default setState() method to update UI & store switch on/off data using getStorage

main.dart

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

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final switchData = GetStorage();

   bool isSwitched = false;

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

    if(switchData.read('isSwitched') != null)
      {
        setState(() {
          isSwitched = switchData.read('isSwitched');
        });
      }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Switch(
                value: isSwitched, onChanged: (value)
               {
                  setState(() {
                        isSwitched = value;
                        switchData.write('isSwitched', isSwitched);
                  });
                }
            ),
          ],
        ),
      ) ,
    );
  }
}




Flutter Switch button Example using getx state management & store on/off data of switch using getstorage

Create new dart File by name ‘GetXSwitchState’ or any name as you want

[project] > lib (right click) > New > Dart File

GetXSwitchState.dart

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';


class GetXSwitchState extends GetxController{
 
  // a variable to On Off Switch in flutter
  var isSwitcheded = false;
  
  // instance of GetStorage, to store data in key value pair.
  final switchdatacontroller = GetStorage();

  GetXSwitchState(){
    print("Constructor called");
    // when user re-visit app, we check previous state of app weather it was on or off.
    if(switchdatacontroller.read('getXIsSwitched') != null){
      isSwitcheded = switchdatacontroller.read('getXIsSwitched');
      update();
    }
  }
  // called when user click on switch to on/off it
  changeSwitchState(bool value){

    isSwitcheded = value;

     // store data in getstorage true or false 
     //here in key 'getXIsSwitched' we store bool type either true or else 
     // if true then switch is ON else OFF
    switchdatacontroller.write('getXIsSwitched', isSwitcheded);

    // update the UI
    update();
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_getx_storage/GetXSwitchState.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

void main() async {
  await GetStorage.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
     // Create a instance of GetXSwitchState class
   final GetXSwitchState getXSwitchState = Get.put(GetXSwitchState());
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(" Getx State Management Switch"),
            // we are wraping the switch with GetBuilder so that it keep observing any change need to be done
            GetBuilder<GetXSwitchState>(builder: (_) => Switch
              (value: getXSwitchState.isSwitcheded,
                onChanged: (value){
                   getXSwitchState.changeSwitchState(value);
                }))

          ],
        ),
      ) ,
    );
  }
}


In above code, we have create a instance object of GetXSwitchState, that will used to get data from it.
Then we are wraping the switch with GetBuilder so that it keep observing any change need to be done & update the UI as per user action.


Recommended Flutter Articles

Basic of Flutter GetX – Introduction to GetX Library

Flutter Dynamic theme change using GETX

Getx State Management

Flutter local notifications using awesome notification package

0

Hi Guys, Welcome to Proto Coders Point, In this flutter tutorial we will learn how to show local notification in flutter by using awesome notification package.

Output of below source code main.dart

flutter local notification example

About Awesome Notification – flutter package

Flutter awesome notification is a very useful & complete solution, when it comes in implementation of notification in flutter weather it’s a local notification or a push notification in flutter through firebase or any other cloud messaging services.

Let’s have a look into feature of awesome notifications

  • Support in creating local notification on Android, iOS and Web.
  • With few lines of code integrate firebase push notification.
  • Notification can be customized as per needs.
  • Add Image, custom sound, Action button & more.
  • OnForeground, Background or even when app is force stopped notification can be invoked.
  • Scheduled Notifications.

Video Tutorial on Flutter Local Notificaton.

How to show/create local notification in flutter

1. Create a new Flutter Project.

Jus open any existing flutter project or create a new flutter project. In my case I make use of Android Studio IDE to build flutter application.

Android Studio > File > New > New Flutter Project ( give name to project and finish ), your project will be ready.

2. Add Awesome_Notification dependencies.

Now, Navigate to pubspec.yaml file & under dependencies add flutter awesome_notification package.

dependencies:   awesome_notifications: ^0.0.6+7 

Then hit pub get button on top of right hand side of IDE. It will download the package into your flutter project as external plugin.

3. import the package class.

Then once you have added the dependencies now you have to import it in main.dart file.

import 'package:awesome_notifications/awesome_notifications.dart';

4. initialize the AwesomeNotification class.

Then initialize awesomenotifications().initialize() before running the app runApp(MyApp()); in void main().

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  AwesomeNotifications().initialize(
      null, // icon for your app notification
      [
        NotificationChannel(
          channelKey: 'key1',
          channelName: 'Proto Coders Point',
          channelDescription: "Notification example",
          defaultColor: Color(0XFF9050DD),
          ledColor: Colors.white,
          playSound: true,
          enableLights:true,
          enableVibration: true
        )
      ]
  );
  runApp(MyApp());
}

NotificationChannel Properties.

propertytypedescription
channelKey:StringA Key to identity noti..
channelName:StringA Name of your channel notification
channelDescription:StringA description about the channel
playSound:boolturn on notification sound. true/false.
soundSource:Stringurl or path of sound file
enableLights:boolenable notification light on/off
ledColor:ColorSet a color for notification led light
enableVibration:boolphone will vibrate when notification arrive.

5. Create Notification.

1. [Snippet Code] Notification with only title & body text.

 

AwesomeNotifications().createNotification(
        content: NotificationContent(
          id: 1,
          channelKey: 'key1',
          title:'Title for your notification',
          body: 'body text/ content'
        )
    );

2. [Snippet Code] Notificaton with title,body & a Image NotificationLayout.

AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 1,
        channelKey: 'key1',
        title: 'This is Notification title',
        body: 'This is Body of Noti',
        bigPicture: 'https://protocoderspoint.com/wp-content/uploads/2021/05/Monitize-flutter-app-with-google-admob-min-741x486.png',
        notificationLayout: NotificationLayout.BigPicture
      ),
  );

3. [Snippet Code] Scheduled Notification.

 String timezom = await AwesomeNotifications().getLocalTimeZoneIdentifier(); //get time zone you are in

AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 1,
        channelKey: 'key1',
        title: 'This is Notification title',
        body: 'This is Body of Noti',
        bigPicture: 'https://protocoderspoint.com/wp-content/uploads/2021/05/Monitize-flutter-app-with-google-admob-min-741x486.png',
        notificationLayout: NotificationLayout.BigPicture
      ),
   schedule: NotificationInterval(interval: 2,timeZone: timezom,repeats: true),
  );

CreateNotification class accept 3 parameters content, schedule and List of actionButtons, where content is required to be specified.

In Content: we are passing NotificationContent which then needs some data properties such as id, channelKey, title & body, and there are many other properties which can be used to customize local notification such as showing a image by using bigPicture properties to show image in notification.

Scheduling a local notification in flutter

As you see in above snippet code, we have used schedule property in createNotification(content: …., schedule:…).

You can easily set a scheduled notification by using schedule property inside createNotification class. In schedule you can make use of NotificationInterval to schedule.

schedule – NotificationInterval properties
propertydescription
intervalinitial notification show time in seconds.
timeZoneyour current location timezone
repeat (type bool)show notification keep repeating after certain seconds, as specified in interval.

NotificationContent properties

propertytypeDescription
idintA unique number identify notification.
channelKeyStringA uniget key to identify the notification.
titleStringA header title text.
bodyString Text Content
displayOnBackgroundboolset weather noti should be displayed when user is not using your app.
displayOnForegroundbool set weather noti should be displayed when user is using your app.
iconString icon for your app notification.
bigPictureStringurl/path of image to show notification thumbnail.
autoCancelboolnoti should go when user top on it.
backgroundColorColor set a custom color to notify.

How to open NotificationPage when user click on Notification – flutter

So the below snippet code, will be listening to user click event & when user click on notification app will get opened & user will be navigated to ‘/NotificationPage’.

AwesomeNotifications().actionStream.listen((receivedNotifiction)
{
                  Navigator.of(context).pushNamed(
                    '/navigationPage',
                  );
});

Complete Source Code of Local Notification with Image.

Video Tutorial on Local Notification in flutter.

main.dart

import 'package:flutter/material.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:notification_example/NavigationPage.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
          channelKey: 'key1',
          channelName: 'Proto Coders Point',
          channelDescription: "Notification example",
          defaultColor: Color(0XFF9050DD),
          ledColor: Colors.white,
          playSound: true,
          enableLights:true,
          enableVibration: true
        )
      ]
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       routes: {
         '/navigationPage' :(context)=>NavigationPage()
       },
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: (){
                Notify();  //localnotification method call below

                   // when user top on notification this listener will work and user will be navigated to notification page
                AwesomeNotifications().actionStream.listen((receivedNotifiction){
                  Navigator.of(context).pushNamed(
                    '/navigationPage',
                  );
                });
              },
              child: Text("Local Notification"),

            ),
          ],
        ),
      ),
    );
  }


}



void Notify()  async{
  String timezom = await AwesomeNotifications().getLocalTimeZoneIdentifier();

 await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 1,
        channelKey: 'key1',
        title: 'This is Notification title',
        body: 'This is Body of Noti',
        bigPicture: 'https://protocoderspoint.com/wp-content/uploads/2021/05/Monitize-flutter-app-with-google-admob-min-741x486.png',
        notificationLayout: NotificationLayout.BigPicture
      ),
   schedule: NotificationInterval(interval: 2,timeZone: timezom,repeats: true),
  );


}