Home Blog Page 65

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


}





Connecting Flutter Android & iOS to Firebase & integrate push notification

0
flutter firebase push notification using awesome notificatiion package
flutter push notification

Hi Welcome to Proto Coders Point, In this firebase flutter tutorial, we will learn how to integrate firebase notification in your flutter app.

Note: We’re going to use ‘awesome_notification package‘.

This Article, is a step-by-step tutorial on how to add flutter project to firebase or how to connect flutter project to firebase console & Then code for push notification in flutter app with complete source code at bottom of this article.

firebase cloud push notification
firebase cloud push notification

What is a push Notification?

A push notification is a way of communication with your app user/customer. Now a days each & every business app, implement push notification into there application so that user get re-engaged to app whenever they get important push notification updates.
Now firebase push notification technology is been rapidly growing in market to communicate with customer/app user.

Let’s quickly start by creating new flutter project & connecting flutter project to firebase.

How to connect flutter project to firebase console for cloud messaging

Video Tutorial

1. Create a new flutter project

Open any existing flutter project, where you want to add firebase push notfication or just create a new flutter project. My favorite IDE is Android Studio, you can choose your favorite IDE to build Flutter Project.

File > New > New Flutter project( give a good name to your flutter project & finish)

2. Add Firebase to your flutter app

Visit firebase.google.com, SignIn with your Google Account & go to firebase console.

Add Project

click on Add Project to create new firebase project for your flutter app.

firebase create new project

Give a good name for firebase project

creating new firebase project

Hit create project button

Then, now our firebase project is ready, now we use need to connect our flutter project to firebase project.

3. [ANDROID] Adding Firebase to your flutter android module

To add android module of your flutter project click on android icon button on firebase console as show in below screenshot.

how to add flutter android module to firebase project

1. Register app in firebase project console

To get android package name, go to your flutter project
[project] android > app > src > main > AndroidManifest.xml as shown in below screenshot.

Copy the package name & paste in “Android Package name” for registration of your app.

2. Download google-services.json that firebase provides

3. copy/paste the google-services.json file in your flutter android module

Now, copy/paste firebase generated google-services.json file into [project] > android > app [ paste here ]. Refer below screenshot to understand where to paste google-services.json file.

where to paste google-services in flutter project

4. Add Firebase SDK

We need google services to load google-services.json file, so add a classpath of google service in your android module

project-level build.gradle file

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // add this line
    classpath 'com.google.gms:google-services:4.3.8'
}

then at bottom of project level build gradle.

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
where to add google services classpath
google services classpath

app-level build gradle

firebase bom, analytics
apply plugin: 'com.google.gms.google-services'
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
}

Now, We are done with adding Flutter Android Module to Firebase. Now let’s add flutter iOS module to firebase.

3. [iOS] Adding Firebase to your flutter iOS module[iphone]

1. connecting flutter iOS to firebase

Just like we did in android firebase connection, now click on iOS button in firebase console.

2. Register app – Add firebase to ios module of flutter.

where to find bundle ID of iOS flutter?

In iOS the package name key is CFBundleIdentifier in Info.plist

<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>

Which is found in Runner.xcodeproj/project.pbxproj

PRODUCT_BUNDLE_IDENTIFIER = com.example.notificationExample;

3. Download GoogleService-info.plist and paste it in iOS

where to paste google services info plist

4. Add firebase SDK using pod

5. ios firebase initialization FirebaseApp.configure()

Hit the next button, now run your flutter project with mobile device connected to internet, Hurrrryy..!!! your Flutter android & iOS module is now connected to firebase project.

Now you have successfully added your flutter project into firebase console.



Integrate firebase push notification in flutter

Now let’s start working with integrating firebase cloud messaging i.e. push notification in flutter.

1. Add dependencies required

In your flutter project open pubspec.yaml file & add this 3 dependencies that are required.

dependencies:
  awesome_notifications: ^0.0.6+7
  firebase_core: ^1.2.1
  firebase_messaging: ^10.0.1

then hit pub get, to download above package into your flutter project.

2. Initialization of Firebase services and AwesomeNotification

Firebase initialization

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(); // initialize firebase before actual app get start.

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); 

  runApp(MyApp());
}

FirebaseMessaging.onBackgroundMessage will keep track of incoming push notification from firebase.
Then it will transfer the message to firebaseMessagingBankgroundHandler with message parameter.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  print("Handling a background message: ${message.messageId}");

  //call awesomenotification to how the push notification.
 AwesomeNotifications().createNotificationFromJsonData(message.data);
}

Awesome Notification initialization

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // firebase initialization

  AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
            channelKey: 'basic_channel',
            channelName: 'Basic notifications',
            channelDescription: 'Notification channel for basic tests',
            defaultColor: Color(0xFF9D50DD),
            ledColor: Colors.white
        )
      ]
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  runApp(MyApp());
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.


  print("Handling a background message: ${message.messageId}");

  // Use this method to automatically convert the push data, in case you gonna use our data standard
  AwesomeNotifications().createNotificationFromJsonData(message.data);
}

Then once onBackgroundMessage detect any incoming message i.e. push notification message from firebase cloud messaging, you can use RemoteMessage to show notification to user using AwesomeNotification package.

AwesomeNotifications().createNotificationFromJsonData(message.data);

optional: If you want to show notification to users locally, when users performer some action in app, then you can use local notification that can we done easily by awesome notification.

AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 10,
          channelKey: 'basic_channel',
          title: 'Simple Notification',
          body: 'Simple body',
          bigPicture:'assets://images/protocoderlogo.png'
      )
  );


Complete Source code – Flutter Push Notification using firebase & awesome notification package

firebase push notification example
firebase push notification example

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:awesome_notifications/awesome_notifications.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  AwesomeNotifications().initialize(
      null,
      [
        NotificationChannel(
            channelKey: 'basic_channel',
            channelName: 'Basic notifications',
            channelDescription: 'Notification channel for basic tests',
            defaultColor: Color(0xFF9D50DD),
            ledColor: Colors.white
        )
      ]
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);


  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(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {


  int _counter = 0;

  void _incrementCounter() {
    setState(() {

      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            ElevatedButton(onPressed: (){
              //local notification 
               Notify();
            }, child: Text("Notify"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

void Notify() async{
  // local notification
  AwesomeNotifications().createNotification(
      content: NotificationContent(
          id: 10,
          channelKey: 'basic_channel',
          title: 'Simple Notification',
          body: 'Simple body',
          bigPicture:'assets://images/protocoderlogo.png'
      )
  );

}


Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {

  print("Handling a background message: ${message.messageId}");

  //firebase push notification
  AwesomeNotifications().createNotificationFromJsonData(message.data);
}

How to submit app-ads.txt file – admob

0
how to fix app-ads.txt file

Hi Guys, Welcome to Proto Coders Point.

This Blog Post is on how to submit app-ads.txt file for admob verification to show ads on your Application, So let’s Begin.

Video Tutorial

Establish a app company Website

A App must have a website so that your app user can visit the website & learn more about your company and get knowledge of your application.

You should have a company website to host app-ads.txt file with a domain name.

Ofcourse, there are many alternative way to submit app-ads.txt file for free without hosting a website, such as by using app-ads-txt.com, Blogger.com and many other way: But I recommend you to do this with your own company domain website, Because it looks genuine to your app user & also google recommend you to establish your own website, instead of using any third party to fix app-ads.txt.

How to create app-ads.txt file?

look at the image below for Example of app-ads.txt.

app-ads.txt format

Note: Check the name file name must be (app-ads.txt) and the content within it must be as per format given by IAB tech Lan in order to get verified successfully.

How to create app-ads.txt file

  1. Create a document with extension .txt file.
  2. name the document as app-ads.txt.
  3. SignIn to Admob account
  4. Navigate to App > View all aps > app-ads.txt tab.
  5. click on how to setup app-ads.txt button.
  6. you will find a code snippet code “copy it
  7. and paste the code snipper into your app_ads.txt document.

Publish the app-ads.txt file on your app website

Now, Once you have created app-ads.txt file you need to publish it on your website.
just upload the app-ads.txt file on root directory in website.

Uploading app-ads.txt to your website hosting in root directory
Eg: www.domain-name.com/app-ads.txt

Note: make sure your the exact website domain is listed on Google Play Console or App Store.

Now wait for at least 25 hours for admob crawler to crawl to your website app-ads.txt file.

Hurry, your have successfully sumbited and fixed the app-ads.txt file requirement for admob ads.

admob has successfully verified your app-ads.txt file