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.
======== 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
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.
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
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,)
],
),
);
}
}
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.
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
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.
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
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.
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
property
description
interval
initial notification show time in seconds.
timeZone
your current location timezone
repeat (type bool)
show notification keep repeating after certain seconds, as specified in interval.
NotificationContent properties
property
type
Description
id
int
A unique number identify notification.
channelKey
String
A uniget key to identify the notification.
title
String
A header title text.
body
String
Text Content
displayOnBackground
bool
set weather noti should be displayed when user is not using your app.
displayOnForeground
bool
set weather noti should be displayed when user is using your app.
icon
String
icon for your app notification.
bigPicture
String
url/path of image to show notification thumbnail.
autoCancel
bool
noti should go when user top on it.
backgroundColor
Color
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’.
This Article, is a step-by-step tutorial on how to add flutter project to firebase orhow 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
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.
Give a good name for 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.
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.
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.
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);
}
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.
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.
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
Create a document with extension .txt file.
name the document as app-ads.txt.
SignIn to Admob account
Navigate to App > View all aps > app-ads.txt tab.
click on how to setup app-ads.txt button.
you will find a code snippet code “copy it“
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