Google search engine
Home Blog Page 52

Firebase Storage in Flutter

0

🤔 Did you know ?

In the old days, if people wanted to store images into Firebase, they would Base64 encode these images into massive strings, and then try and save them that way.

This wasn’t very efficient. But these days, we’ve got Firebase Storage, which lets you store and retrieve large pieces of user-generated content like photos, music, and movies all without needing your own servers.

Sound intriguing?

Stick around & find out how !!


Content

Setting Up!

Firebase Storage

Features of Firebase Storage

Adding Images to Firebase Storage

Linking Firebase Storage with Firestore

Retrieving Images form Firebase Storage

Deleting Images

Resources


Setting Up !

STEP 1 : Go through this on how to add Firebase to your projectLinking Firebase Storage With Firestore

Firebase Storage

STEP 2: Include this plugin in dependencies in pubspec.yaml

firebase_storage : 

Firebase Storage lets you store and retrieve user-generated content like images, audio, and video, all without the need of a server.

We all know from experience,that people love to share things about themselves, such as photos, videos, and GIFs that express their feelings.

Features of Firebase Storage

  • Firebase storage API lets you upload your users’ files to our cloud so they can be shared with anyone else!
Sharing of files/images
  • And if you have specific rules for sharing files with certain users, you can protect this content for users logged in with Firebase authentication.
Specific User Rules
  • Security, of course, is the first concern. All transfers are performed over a secure connection.
Secured Connection
  • All transfers with API are robust and will automatically resume in case the connection is broken. This is essential for transferring large files over slow or unreliable mobile connections.
Transfer paused over unreliable connections
  • And, finally, storage, backed by Google cloud storage, scales to petabytes — that’s billions of photos — to meet your app’s needs. So you will never be out of space when you need it.
Storage scales to petabytes !!

Demo Application

We will develop a simple profile application in which we will see how to pick images from the image library and also, see how to store, retrieve & delete the selected images on Firebase. To perform these actions, I shall be using these plugins. Do these plugins in dependencies in pubspec.yaml

image_picker :
firebase_storage :

Linking Firebase Storage With Firestore

We will be importing these packages —

import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';

Adding Images to Firebase Storage

We can use image picker to get our images from gallery.

So to add the selected images to Firebase Storage, we can create a edit icon to save the images to storage uploadPic

https://gist.github.com/Anirudhk07/7098562bad53ecbdb27b566cd54d1810#file-upload-dart

Linking Firebase Storage With Firestore

After onComplete property, we can check if the image were successfully added or not:

https://gist.github.com/Anirudhk07/795ede5a5509c5fcc7444437bad8f1e3#file-link-dart

Saving Images form Firebase Storage

We can use a raised button to retrieve our images that we uploaded which on pressed

RaisedButton(    
child: Text("Save Image"),
onPressed: () async {
if (_image != null)
{
StorageReference ref = FirebaseStorage.instance.ref(); StorageTaskSnapshot addImg = await ref.child("image/img").putFile(_image).onComplete;
if (addImg.error == null) { print("added to Firebase Storage"); }
} }),

Deleting Images

Now, let’s say you have users in your application, each user will have a profile image, if a user gets deleted then you want to delete the image also from Firebase Storage. In that case, you can do the following, for example:

https://gist.github.com/Anirudhk07/bfc2075bba24cce47376cf07cdc8cb6b#file-delete-dart

You can visit the whole code over here —

flutter-devs/Flutter-Firebase-Storage
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build…github.com

Happy Fluttering!

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Resources

firebase_storage | Flutter Package
A Flutter plugin to use the Firebase Cloud Storage API. For Flutter plugins for other Firebase products, see README.md…pub.dev

image_picker | Flutter Package
A Flutter plugin for iOS and Android for picking images from the image library, and taking new pictures with the…pub.dev

flutter-devs/Flutter-Firebase-Storage
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build…github.com


Related: Maintain Activity Log in Firebase Using FlutterFlow

Related: Using Firebase Firestore in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Adding Responsiveness to your Flutter widgets

0

Responsive UI changes the UI of the application screen/widget according to the size of the different mobile screens. Responsive UI is very useful when the same application is made for mobile, web, table, watch(wear apps). Responsive UI rearrange the UI according to the orientation of the device and size.

Need Of Responsive UI :

  1. Highly flexible design
  2. Provides optimized view according to the screen constraints or Orientation
  3. Minimalism in design
  4. Relatively cheap
  5. Easy for SEO

Table of content

Contributing factors used to create responsive UI:-

Using LayoutBuilder

Using MediaQuery

Using AspectRatio

Using FittedBox

Using FractionallySizedBox

Using OrientationBuilder

Github Link


LayoutBuilder

Layout Builder changes the UI according to the size constraints of the device screen. Layout builder takes a builder which return a widget and change the view according to the condition specified by the user.

builder takes a Buildcontext and BoxConstraints.

Here we are using the maxWidth to change the UI of the screen. Whenever the width of the screen is less than 601 or greater than 600 the layout builder will return the VerticalView() widget and HorizontalView() widget respectively.

LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 601) {
return HorizontalView();
} else {
return VerticalView();
}},),

BoxConstraints

  1. Creates box constraints with the given constraints.
  2. Click here to read more about the BoxConstraints class.
  3. We can also get the maxWidth, minWidth, maxHeight, minHeight.

We can also change the UI by getting the Height and Width of the device screen. Example:-

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 601) {
return HorizontalView();
} else {
return VerticalView();
}},),);}}

Widget VerticalView() {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue.withOpacity(0.3),
elevation: 0,
title: Container(
width: 150,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(Icons.favorite_border),
Icon(Icons.bookmark_border),
Icon(Icons.star_border),
],),),),

body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[Text("Hello"), Text("World")],),),);}

Widget HorizontalView() {
return Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
NavigationRail(
backgroundColor: Colors.blue.withOpacity(0.3),
destinations: [
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('First'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.book),
label: Text('Second'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),],
selectedIndex: 1,),
Text("Hello"),
Text("World ")
],),),);}

MediaQuery

MediaQuery is the class that enables us to query the current size of the media. We can use MediaQueryData.size it to get the size of the screen. This will automatically rebuild whenever the MediaQueryData changes.

MediaQueryData mediaQueryData(BuildContext context) {
return MediaQuery.of(context);
}

Size size(BuildContext buildContext) {
return mediaQueryData(buildContext).size;
}

double width(BuildContext buildContext) {
return size(buildContext).width;
}

double height(BuildContext buildContext) {
return size(buildContext).height;
}
  1. MediaQuery.of(context) returns the MediaQueryData(eg. size of the screen, brightness mode, devicePixelRatio, etc).
  2. MediaQuery.of(context).size.width gives us the width.
  3. MediaQuery.of(context).size.height gives us the height of the current media.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 601) {
return HorizontalView(
height(context) * 0.25, width(context) * 0.25);
} else {
return VerticalView(height(context) * 0.25, width(context) * 0.25);
}
},
),
);
}
}
Widget VerticalView(double height, double width) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue.withOpacity(0.3),
elevation: 0,
title: Container(
width: 150,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(Icons.favorite_border),
Icon(Icons.bookmark_border),
Icon(Icons.star_border),
],
),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
width: width,
height: height,
color: Colors.orange,
child: Center(child: Text("Hello")),
),
Container(
width: width,
height: height,
color: Colors.orange,
child: Center(child: Text("World")),
)
],
),
),
);
}
Widget HorizontalView(double height, double width) {
return Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
NavigationRail(
backgroundColor: Colors.blue.withOpacity(0.3),
destinations: [
NavigationRailDestination(
icon: Icon(Icons.favorite_border),
selectedIcon: Icon(Icons.favorite),
label: Text('First'),
),
NavigationRailDestination(
icon: Icon(Icons.bookmark_border),
selectedIcon: Icon(Icons.book),
label: Text('Second'),
),
NavigationRailDestination(
icon: Icon(Icons.star_border),
selectedIcon: Icon(Icons.star),
label: Text('Third'),
),
],
selectedIndex: 1,
),
Container(
width: width,
height: height,
color: Colors.orange,
child: Center(child: Text("Hello")),
),
Container(
width: width,
height: height,
color: Colors.orange,
child: Center(child: Text("World")),
)
],
),
),
);
}

AspectRatio

Creates a widget with a specific aspect ratio. The aspectRatio argument must not be null. The aspect ratio is expressed as a ratio of width to height. For example, a 19:7 width: height aspect ratio would have a value of 19.0/7.0.

class ApRatio extends StatelessWidget {
final double aspectRatio;

ApRatio({@required this.aspectRatio});

@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: aspectRatio,
child: Container(
color: Colors.orange,
child: Center(child: Text("Aspect Ratio")),
),
);
}
}

FittedBox

It creates a widget that scales and positions its child within itself according to fit. The fit and alignment arguments must not be null.

We can also set alignment property to properly align the child(eg. alignment: Alignment.bottomRight or alignment: Alignment(1.0, 1.0))

BoxFit Enums

BoxFit enum
How a box should be inscribed into another box. See also: applyBoxFit, which applies the sizing semantics of these…api.flutter.dev

Card(
child: Row(children: [
Text(
"Without fittedBox",
style: TextStyle(fontSize: 25),
),
Container(
height: 200,
child: Image.network(
"https://lh3.googleusercontent.com/-svwfeFI7WnY/XvHmVb955QI/AAAAAAAAHvc/K3JwOtoUkNkalWy_CY9DJRgxfKddCUQswCK8BGAsYHg/s0/Untitled-3.png"),
),
]),
),
FittedBox(
child: Card(
child: Row(
children: [
Text(
"With fittedBox",
style: TextStyle(fontSize: 25),
),
Container(
height: 200,
child: Image.network(
"https://lh3.googleusercontent.com/-svwfeFI7WnY/XvHmVb955QI/AAAAAAAAHvc/K3JwOtoUkNkalWy_CY9DJRgxfKddCUQswCK8BGAsYHg/s0/Untitled-3.png"),
),
],
),
),
),

FractionallySizedBox

It creates a widget that sizes its child to a fraction of the total available space.
If non-null, the widthFactor and heightFactor arguments must be non-negative.

Properties

  1. heightFactor (It is the height of the child. Its value lies between 0 to 1. If heightFactor: 0.5, it means the height of the child is 50% of the total height of the screen.)
  2. widthFactor (It is the width of the child. Its value lies between 0 to 1. If widthFactor: 0.5, it means the height of the child is 50% of the total width of the screen.)
  3. alignment ( It defines the position of the given child.)
FractionallySizedBox(
heightFactor: 1,
widthFactor: 0.25,
child: Container(color: Colors.green),

//in a row or column
Container(
height: 50.0,
child: Column(children: [
Flexible(
child: FractionallySizedBox(
heightFactor: 1,
widthFactor: 0.5,
child: Container(color: Colors.orange),
),
),
Flexible(
child: FractionallySizedBox(
heightFactor: 1,
widthFactor: 0.25,
child: Container(color: Colors.green)),
),
Flexible(
child: FractionallySizedBox(
heightFactor: 1,
widthFactor: 0.15,
child: Container(color: Colors.blue)),
),
])),

OrientationBuilder

It Creates an orientation builder. The builder argument must not be null.

The orientation class provides us the landscape view, portrait view. We can use these views to check the device orientation and then we can change the app screen view as follows.

OrientationBuilder(
builder: (context, orientation) {
if (orientation == Orientation.landscape) {
return HorizontalView(
height(context) * 0.25, width(context) * 0.25);
} else {
return VerticalView(height(context) * 0.15, width(context) * 0.5);
}
},
),

Closing Thoughts

Responsive UIs are a Quintessential tool in modern applications as they provide us with the ease of customizing the User-Interface of the app as per the device’s screen size and orientation ensuring that the same app can be apparent run into multiple devices without any hindrance as the app will respond by rearranging the UI accordingly. The key purpose of this article is to avail you of an Insight into How we can create Responsive UIs In Your Flutter Widgets.

If you have not used the Responsive Approach, I hope this article has provided you with content information about what’s all about the topic, and you will give it — a Try. Initiate using Responsive UIs for your apps. !!!

Github Link:

flutter-devs/responsive_UI
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Thanks for reading this article ❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Dark Mode Implementation

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Trace Network Calls In Flutter

0

Tracing network calls in flutter is not an inbuilt feature where you observe and read your network requests, however, flutter provides testing and observation feature for UI and facilitating testing only for widgets makes it an ill-equipped framework, however, Flutter is now on the ground with DevTools where it provides accessing network request easy but there are also different techniques to do the same. so in order to full fill our requirement we use some techniques to sort it out.

Is Tracing Call Necessary?

As you know to make the request and receiving network call is a necessity for app development as there is nothing possible without exchanging data and it is important to observe data flow that’s why Tracing Network call is Necessary.

How Can We do this?

There are multiple techniques to do it like Devtools, Alice, Flipper, debug Proxy to trace network calls, and today we learn some of them so let’s see how to do it.

1. DevTools :

DevTools is a suite of performance and debugging tools for Dart and Flutter. It’s currently in beta release but is under active development. now the question is what we can do with the DevTools, so there are various features we can do with it

  • Inspect the UI layout and state of a Flutter app.
  • Diagnose UI jank performance issues in a Flutter app.
  • CPU profiling for a Flutter or Dart app.
  • Network profiling for a Flutter app.
  • Source-level debugging of a Flutter or Dart app.
  • Debug memory issues in a Flutter or Dart command-line app.
  • View general log and diagnostics information about a running Flutter or Dart command-line app.

How to Use it

for using it in your flutter application first use need to install dev tools in your project for this you need to run this command in your terminal

flutter pub global activate devtools

it installs all required setup for your app, now you need to launch DevTools application server by running the command

flutter pub global run devtools

now you will find something like this in your commands, this is a local server of DevTools where you need to put a link to connect your app

and by clicking on the local server you will find this window

then start your application for debugging by running this command

flutter run

here you will find the link which you need to fill in that browser window which was opened by that local server host

 http://127.0.0.1:50976/Swm0bjIe0ks=/

you need to put this kind of URL into that DevTools folder and you will find this kind of window.

here you can inspect all available features like with tools like performance, debugger, network, and many more. Here it is the network tracing feature of it

here in the image, you can see all the requests and received responses to the app and everything which you need to know can be accessed easily.so it was a general introduction and installing of DevTools and working on it.

2. Alice:

Alice is an HTTP inspector for Flutter and based like Chuck-tools. Alice basically Alice intercepts and exposes the interface of inspecting call details of HTTP calls. you can open the inspector from notification which we receive when we make network calls. If I talk about the best suitability and work easiness then it is best suited for Dio plugin because Dio is the most advanced HTTP client for Dart language however Alice can also be used with other HTTP clients and it gets refreshed every time when new requests come.

How to install it

First, you need to install Alice by adding a dependency in yaml file

dependencies:
alice:

then run command

$ flutter packages get

and import this into your dart file

import 'package:alice/alice.dart';

now you are ready to use Alice so firstly you need to create an instance of it

Alice alice = Alice(showNotification: true, darkTheme: false,navigatorKey: navigationKey);

there are different options like notification, dark theme, and navigation key you can customize these things according to you as if you want to see the notification when a request comes in then true else false, same as with the dark theme and navigation key is important because it opens the inspector screen let’s see how and where we use navigation key.

Navigation is used in the material widget when you create your own unique global key and use it into the material widget.

GlobalKey<NavigatorState> navigationKey = GlobalKey<NavigatorState>();

after creating a global key we use it into the material widget

MaterialApp(
navigatorKey: navigationKey,
debugShowCheckedModeBanner: false,
title: 'Flutter PWA',
theme: ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
darkTheme: ThemeData(brightness: Brightness.dark),
home: HomePage(),
);

now you need to go the methods where you are making network calls if it is Dio then it is very easy to use it.

Dio dio = Dio();
dio.interceptors.add(alice.getDioInterceptor());

Dio consists of special feature which allows it to add interceptors with ease and it exposes special interceptors which you need to be pass to Dio instance.

as most of the people generally use HTTP to make network calls so if you want to use Alice with HTTP you need to log every request and response manually.

Here are some examples :

If you’re using HttpClient from dart:io package:

httpClient
.getUrl(Uri.parse("https://jsonplaceholder.typicode.com/posts"))
.then((request) async {
alice.onHttpClientRequest(request);
var httpResponse = await request.close();
var responseBody = await httpResponse.transform(utf8.decoder).join();
alice.onHttpClientResponse(httpResponse, request, body: responseBody);
});

If you’re using http from http/http package :

http.get('https://jsonplaceholder.typicode.com/posts').then((response) {
alice.onHttpResponse(response);
});

If you have other HTTP clients you can use a generic HTTP call interface:

AliceHttpCall aliceHttpCall = AliceHttpCall(id);
alice.addHttpCall(aliceHttpCall);

if you have set your notification off and you want to access the inspector then you can use this method to open the inspector.

alice.showInspector();

You can find the complete example from here

alice | Flutter Package
Alice is an HTTP Inspector tool for Flutter which helps debugging http requests. It catches and stores http requests…pub.dev

so if you are done with this installation now its time to test the setup so once we run our app we get the notification in the device and after clicking on it we navigate to the screen where we find

here in the image, it is showing a network request made by the app and you can see the whole status of it by click on it, here when you click on the request you get 4 tabs for different pieces of information

Details of Tabs :

Overview: It shows the general information of HTTP call like methods, endpoint, request, and response time, amount of bytes and duration, connection security.

Request: It shows details of the HTTP request as time, request body and headers, amount of bytes sent, content type,

Response: It shows details of the HTTP response as time, amount of bytes received, status code, response body, and headers.

Error: It shows information about the error if any occurred, this tab will show errors only when you’re using Dio plugin

we also get different options of delete, stats, and save when we click on the toolbar we can use according to need.

Conclusion

In this article, we have discussed two techniques to intercept network call in the flutter where DevTools is official Flutter feature both have there own advantages and disadvantages in DevTools you don’t need to write the code for setup and you can easily do your work and it also provides features to inspect your UI and widgets while in the Alice you need to set up everything but once you get installed it, it becomes easy to use you can inspect each and everything on your respective devices.

So here only two techniques have been explained and all remaining techniques will be covered in upcoming blogs so stay connected with us. Thanks.


If this article has helped you a bit and found interesting please clap!👏

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Local Push Notification in Flutter

In today’s world if we look at any live app in the market has the web notification or local notification functionality. This shows the importance of integrating our app with notification functionality. Local Notification is widely used to inform the user about any information or a way to alert the user in realtime without the use of the internet. These notification are pre-scheduled by the developer according to the various actions performed by the user in the app.


Table of Content

Need of Local Push Notification

How to implement Local Notification in Flutter?

Creating a Flutter Local Notification object

Creating initState

Simple Notification

Schedule notification

Big Picture Notifications

Media Notification

Cancel Notification

Github Link


Need of Local Push Notification?

  • Scheduled notification.
  • Setting Up the project
  • No web request is required to display Local notification.
  • No limit of notification per user.
  • Originate from the same device and displayed on the same device.
  • Alert the user or remind the user to perform some task.

How to implement Local Notification in Flutter?

Thankfully in flutter, we had a package to do it. This package provides us the required functionality of Local Notification. Using this package we can integrate our app with Local Notification in android and ios app both.

flutter_local_notifications | Flutter Package
A cross platform plugin for displaying and scheduling local notifications for Flutter applications with the ability to…pub.dev

flutter_local_notifications: ^latest version

install this package into your pubspec.ymal file and don’t forget to import

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Setting Up the project

Edit your AndroidManifest file

Add the following permission to integrate your app with the ability of scheduled notification.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Add this inside the application section

<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

Add vibration permission

<uses-permission android:name="android.permission.VIBRATE" />

Creating a Flutter Local Notification object

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

flutterLocalNotificationsPlugin is our object that we will use to perform various operations.


Creating initState

void initState() {
super.initState();
var initializationSettingsAndroid =
AndroidInitializationSettings('flutter_devs');
var initializationSettingsIOs = IOSInitializationSettings();
var initSetttings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOs);

flutterLocalNotificationsPlugin.initialize(initSetttings,
onSelectNotification: onSelectNotification);
}
  1. AndroidInitializationSettings is a class that initializes the settings for android devices. This class is used to provide an icon for our notification.
  2. IOSInitializationSettings plugin used to initialize the settings for ios devices.
  3. InitializationSettings plugin used to initialize the settings of each platform (Android and ios).
  4. initialize method is used to set the setting according to the platform of the device. If the device is android then the app will work according to the android setting specified and if the platform is ios then it enables all the ios settings. It also has onSelectNotification property which performs the task given on pressing the Notification.
Future onSelectNotification(String payload) {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return NewScreen(
payload: payload,
);
}));
}

NewScreen Widget is a new screen that occurs when the user presses the notification.

class NewScreen extends StatelessWidget {
String payload;

NewScreen({
@required this.payload,
});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(payload),
),
);
}
}

Simple Notification

showNotification() async {
var android = AndroidNotificationDetails(
'id', 'channel ', 'description',
priority: Priority.High, importance: Importance.Max);
var iOS = IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin.show(
0, 'Flutter devs', 'Flutter Local Notification Demo', platform,
payload: 'Welcome to the Local Notification demo');
}
}

AndroidNotificationDetails is a class that contains the details about the notification on Android devices such as priority, importance, channel name, channel description, channel id, sound, vibration, etc. Similarly, IOSNotificationDetails it contains the ios notification details. It is not necessary to provide the details of android and ios, if your app is specific t the android users then you can pass null in the NotificationDetails in ios section. show() method automatically checks for the available platform whether it is ios and android. If the platform is android then it sets the AndroidNotificationDetails as the notification details. show() method takes the id, title, body, NotificationDetails, payload is a string that we will use to pass it as an argument in the onSelectedNotification function to display some text in the new screen related to the type of notification clicked.

Schedule notification

scheduleNotification is a notification which used to perform a scheduled task. This notification occurs at a specified time.

Future<void> scheduleNotification() async {
var scheduledNotificationDateTime =
DateTime.now().add(Duration(seconds: 5));
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel id',
'channel name',
'channel description',
icon: 'flutter_devs',
largeIcon: DrawableResourceAndroidBitmap('flutter_devs'),
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
0,
'scheduled title',
'scheduled body',
scheduledNotificationDateTime,
platformChannelSpecifics);
}

Big Picture Notifications

Future<void> showBigPictureNotification() async {
var bigPictureStyleInformation = BigPictureStyleInformation(
DrawableResourceAndroidBitmap("flutter_devs"),
largeIcon: DrawableResourceAndroidBitmap("flutter_devs"),
contentTitle: 'flutter devs',
summaryText: 'summaryText',
);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'big text channel id',
'big text channel name',
'big text channel description',
styleInformation: bigPictureStyleInformation);
var platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, null);
await flutterLocalNotificationsPlugin.show(
0, 'big text title', 'silent body', platformChannelSpecifics,
payload: "big image notifications");
}

Media Notification

Future<void> showNotificationMediaStyle() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'media channel id',
'media channel name',
'media channel description',
color: Colors.red,
enableLights: true,
largeIcon: DrawableResourceAndroidBitmap("flutter_devs"),
styleInformation: MediaStyleInformation(),
);
var platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, null);
await flutterLocalNotificationsPlugin.show(
0, 'notification title', 'notification body', platformChannelSpecifics);
}

Cancel Notification

cancel() removes the notification of the given id.

Future<void> cancelNotification() async {
await flutterLocalNotificationsPlugin.cancel(0);
}

Conclusion

Local push notification is extremely useful to provide notification or alert about the important task. Local notification can be implemented without the internet. The Scheduled Notification is extremely powerful as they are very fast and very accurate and notify the user as per the time scheduled by the user.

If you are making a reminder app or todo app, then you should use Local Notification. I hope this article has provided you with content information about what’s all about the topic, and you will give it — a Try. Initiate using Local Push Notification for your apps. !!!

Github Link

flutter-devs/local_push_notification
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Local Authentication in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Hybrid Apps-The Future Of Mobile Technology?

0

Mobile apps have been growing Ginormously since their inception. Every day we come across the news of some new app being launched in the market. Though this world of app development is very exciting, sometimes it’s confusing too especially when it puts a question before you while development- whether to go for a native app or hybrid app? Choosing from these two can be very challenging as both of these programming languages — Hybrid and Native, come with their pros and cons.

  • Before getting into the nitty-gritty of Hybrid app technology .
  • Let’s see what is a hybrid app, the buzz which is creating in the market, and how it will be a big differentiator in your business.
Hybrid Apps Vs Native Apps

What are Hybrid Mobile Apps?

The combination of native as well as mobile apps is called the Hybrid apps. Just like native apps, they have to be first downloaded in an app store and then the app can utilize any of the features which a device has. As far as the web app part is considered, they rely on HTML being provided in a browser embedded within the app.

A hybrid app consists of an HTML5 web app within a native ‘wrapper.’ This is a mobile app written using HTML5, CSS3, and JavaScript, and then compiled into native iOS, Android, or other mobile platform using wrapper technologies.

Hybrid apps combine the benefits of the website and the app. Some programmers choose hybrid apps to conveniently incorporate device features such as push, camera, or GPS notifications. They have the extra benefit of obtaining Google’s and Apple’s platform’s customer base since apps are available through the App stores. Because they’re still basically web programs, they’re more economical to develop but might require experts that have more specialized knowledge of the different interfaces and features of their phone.

Why Hybrid Apps are set to Trump Native Apps in the Future?

:: App Store Limitation

Today, releasing a native mobile app involves packaging the code, submitting it to the app store, and waiting for it to be approved. The entire process can take anywhere from two to seven days. This is an eternity in the mobile world. Mobile app developers want to be able to update their mobile apps like their web apps, multiple times a day if necessary. This is not possible with the limitations of app stores, and hybrid apps are the way out.

:: Code Reuse

As most apps have an iOS and an Android version, they are developed using each platform’s preferred programming language — Objective-C or Swift for iOS, and Java for Android. Hybrid apps, on the other hand, let you build mobile apps with the same languages your developers are already familiar with — HTML, JavaScript, and CSS. You can write code once, and deploy it across all your mobile platforms. Mobile app testing equally benefits because you don’t need to write unique test scripts for each app type. Testing against a single codebase also reduces the testing infrastructure you need and simplifies the QA process. With the increasing fragmentation in device types and OS versions, this is becoming a necessity for mobile development.

:: DevOps for Mobile

Finally, hybrid apps let you extend DevOps to your mobile apps, too. They let you go from mammoth quarterly app updates to a bi-weekly cycle, and eventually let you update as frequently as your web app — which is close to impossible with native apps today. To update at this frequency, you’ll need to automate the two key parts of your continuous integration (CI) process — builds and tests. This is where tools like Git, Jenkins, and Appium have a key role to play. When well-integrated, they can let you focus exclusively on developing and testing your app, rather than worrying about mobile platforms’ norms. This gives you the confidence to release multiple times a day, and take ownership of your mobile development process.

Flutter — The revolution in Hybrid Technology

This free and open-source platform allows the developers to build highly-interactive native interfaces on iOS and Android in record time. Its ability to speed up the entire app development process assists the developers in reaching a wider base of audience. let’s understand how this SDK, Software Development Kit, will prove to be beneficial for the app development industry as well:

:: Faster App Development Process

Flutter supports both IOS and Android, making it a feasible option for cross-platform app development. It allows the developers to modify widgets and build a highly engaging native interface. Also, the immensely productive rendering engine makes it a great choice for developing native platforms.

:: Striking User Interface

Having an eye-catching user interface is always a big plus for a mobile app. Flutter features Material Design and Cupertino for Android and iOS apps, respectively, that assist the app developers in building highly engaging apps. These are set of visual and motion-rich widgets that make the app look beautiful and interactive on both platforms. These apps are easy to navigate and extremely user-friendly.

:: Accessible Native Features and SDKs

Flutter further makes your app development journey delightful through native codes, third-party integrations, and platform APIs. You can easily access the native features and SDKs on both platforms and reuse the widely-used programming languages for IOS and Android such as Swift and Kotlin.

:: Highly Reactive Framework

With Google Flutter, you can easily modify the interface by changing the variable in the state. Consequently, all changes will reflect in the UI. Also, Flutter makes it easier and quicker to set up the application compared to React Native.

So, Will Hybrid Apps Replace Native Apps?

We are at a stage of infancy when it comes to choosing between platforms (there are only four — Windows, HTML, iOs, and Android). To conclude, hybrid apps are a much cost-effective way for a company to port over their app. Their technical person does not need to learn a new language or even hire someone to do it.
But on the other side, the user experience in native apps is something that the company cannot ignore. For example, iOS users and developers know the apps inside out. Without customizing the UX for each platform, the apps won’t work the way they worked before, thus, the lack of functionality and eventually losing their app users.


If you are planning to have your own mobile application, website, custom web app designed by a professional design team, or Have any type of query or concern regarding its concept, technical know-how, the best way to get it done then don’t hesitate to reach out to us .

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Adding AdMob to your Flutter App

0

What you’ll learn !

✅How to set up a Firebase project for a Flutter app

✅How to configure the Firebase AdMob plugin

✅How to use banner, interstitial, and rewarded ads in a Flutter app


Content

Setting up a firebase project

Setting up the AdMob app and ad units

Different Ad Types

Firebase AdMob Flutter plugin

Adding helper class for Ads

Initialise AdMob SDK

Resources


Setting up a firebase project

:: Setting up the AdMob app and ad units

Because Flutter is a multi-platform SDK, you need to add an app and ad units for both Android and iOS in AdMob. Before you start, you want to be familiar with the following AdMob glossaries —

Ad unit

Ad unit is a set of ads displayed as a result of one piece of the AdMob ad code. You can create and customize an ad unit in your AdMob account. Each ad unit has a unique identifier, called the ad unit ID. When you implement a new ad unit in your app, you’ll reference the ad unit ID to tell ad networks where to send ads when requested.


STEP 1 : Add an Android app

Use the following instructions to add an Android app to AdMob:

  1. In the AdMob console, click ADD APP from the Apps menu.
  2. When you’re asked ‘Have you published your app on Google Play or the App Store?’, click NO.
  3. Enter Awesome Drawing Quiz in the App name field, and select Android as the platform.

Note : Make a note of your new app ID (ca-app-pub- xxxxxxxxxxxxxxxx~yyyyyyyyyy).

You’ll need to add it to the sample project’s source code to run ads.


STEP 2: Create ad units

To start adding ad units to AdMob:

  1. Select Awesome Drawing Quiz (Android) from the Apps menu in the AdMob console.
  2. Click the Ad units menu.

From the Ad units menu, follow the instructions to create a banner ad, an interstitial ad, and rewarded ad unit.


Banner

Banner ads occupy a spot within an app’s layout, either at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time.

Banner Ad
  1. Click the ADD AD UNIT button.
  2. Select Banner as the format.
  3. Enter android-adq-banner in the Ad unit name field.
  4. Click CREATE AD UNIT to complete the process.

Interstitial

Interstitial ads are full-screen ads that cover the interface of their host app. They’re typically displayed at natural transition points in the flow of an app, such as between activities or during the pause between levels in a game.

Interstitial Ad
  1. Click the ADD AD UNIT button.
  2. Select Interstitial as the format.
  3. Enter android-adq-interstitial in the Ad unit name field.
  4. Click CREATE AD UNIT to complete the process.

Rewarded

Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards.

Rewarded Ad
  1. Click the ADD AD UNIT button.
  2. Select Rewarded as the format.
  3. Enter android-adq-rewarded in the Ad unit name field.
  4. Leave the default for Reward settings.
  5. Click CREATE AD UNIT to complete the process.
✔Important: It usually takes a few hours for a new ad unit to be able to serve ads. If you want to test the ad behavior immediately, then use the preconfigured app ID and ad unit IDs instead.
You can find Test IDs below - 

Test Ads | Android | Google Developers
This guide explains how to enable test ads in your ads integration. It’s important to enable test ads during…developers.google.com


Firebase AdMob Plugin

Now that you have set up the ad mob ads , it’s the time to integrate it to your App !

The firebase_admob plugin supports loading and displaying banner, interstitial, and rewarded ads by using the AdMob API.

The firebase_admob plugin supports loading and displaying banner, interstitial, and rewarded ads by using the AdMob API.

STEP 1 : Pubspec.yaml

...

dependencies:
flutter:
sdk: flutter
google_fonts: ^0.3.9

# Add the following line
firebase_admob: ^0.9.3

...

STEP 2 : Update AndroidManifest.xml

android/app/src/main/AndroidManifest.xml

Add your AdMob app ID by adding a <meta-data> tag and entering com.google.android.gms.ads.APPLICATION_ID. If your AdMob app ID is ca-app-pub-3940256099942544~3347511713, then you need to add the following lines to the AndroidManifest.xml file.

<manifest>
...
<application>
...
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
</application>

</manifest>

Adding Helper Class for ads

Create a new file named ad_manager.dart under the lib directory. Then, implement the AdManager class which provides an AdMob app ID and ad unit IDs for Android and iOS.

Make sure that you replace the AdMob app ID (ca-app-pub-xxxxxx~yyyyy) and the ad unit ID (ca-app-pub-xxxxxxx/yyyyyyyy) with the IDs you created in the previous step.

https://gist.github.com/Anirudhk07/869aa3fe4f7b60fee62dcc3cd341c3ab#file-ad_manager-dart


Initialize AdMob SDK

Congratulations !✨ You have reached the final step towards integrating Ads to your App !

Before loading ads, you need to initialize the AdMob SDK. Open the lib/home_route.dart file, and modify _initAdMob() to initialize the SDK before the game starts.

https://gist.github.com/Anirudhk07/15305bc8ded3d53c9d0591f3abdae4d4#file-admobs-dart

Hurray!! Now you can add banner ad, an interstitial ad, and rewarded ad unit.

To deep dive on how to add banner ad, an interstitial ad, and rewarded ad unit in a Demo App , stay tuned for the next upcoming blog !

Happy Fluttering !! ❤


Resources

firebase_admob | Flutter Package
A plugin for Flutter that supports loading and displaying banner, interstitial (full-screen), and rewarded video ads…pub.dev


If you are planning to have your own mobile application, website, custom web app designed by a professional design team, or Have any type of query or concern regarding its concept, technical know-how, the best way to get it done then don’t hesitate to reach out to us .

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: SMS Using Twilio In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Mixins in Dart: How to use it

0

There are different object-oriented programming (OOP) languages and Dart is one of them, basically, keeping code clean and dry is one of the characteristics of OOP. In OOP you have regular classes, abstract classes, and interfaces but in the dart, there is another hidden feature which is called mixins and this gives you that wow! which sometimes every developer looks for but the question is how?

Basically, the concept of mixins comes into effect when you want to inherit multiple classes at the same time but as you know dart does not allow multiple inheritances (which is a good thing ) and there you stand with two options either create a duplicate method or create mixins, wait….mixins?🤔

What are mixins?

Mixins are simple classes that are instantiated by using mixin to avoid multiple class hierarchies. if we go by definitions there are some quotes here

A mixin declaration introduces a mixin and an interface, but not a class. The mixin introduced by a mixin declaration contains all the non-static members declared by the mixin, just as the mixin derived from a class declaration currently does.


Mixins are a way of reusing a class’s code in multiple class hierarchies.

dartlang.org

Now you might get the sense behind the mixins. So let’s understand it by example

Problem:

To sort out this we will understand the concept of mixin by the real-world example so you can easily understand it.

Suppose we have two animal classes where we have different kinds of animals some of them have some same and some different qualities, for example, there are two classes — alligator and crocodile.

Both of them have similarities in every aspect.

https://gist.github.com/shivanchalaeologic/9881d1e8792f193cb1d6df634e21d990#file-alligator-dart

https://gist.github.com/shivanchalaeologic/881ec1febb4e443b32fb733b3cecf3c1#file-crocodile-dart

Both of them also come into the aquatic animal category but all animals who live in water don’t have the same behavior so here we could create an abstract class that would have the same sort of things that most aquatic animals have.

https://gist.github.com/shivanchalaeologic/f29606d320e7bd51c35b1e786d9a1e0b#file-animal-dart

Now if we mention any other aquatic animal that has some other behaviors then ??? should we create another class of different behavior ???

No, you don’t need because if that animal has some behaviors that reptile class consists and some which it does not then we have only the option to create a new class for that specific animal which will also extend reptile class.

You can do this but as you know flutter does not allow multiple inheritances then mixin comes into effect,

for example, see the code below there is class fish which have qualities like bit and swim but does not have crawl so if it extends that reptile class it would find some feature that it does not require then either fish class should create its own swim and bite method but it is code duplication so we would create Swim, Bite and Crawl as mixin classes.

https://gist.github.com/shivanchalaeologic/7d46d908d727dd6f3f3d774565666973#file-animal-dart

In the above example as you can that using mixin classes does not require any special specifications you can inherit by using with keyword. You can inherit mulitple mixin classes.

But what if you want to limit the use of a particular mixin class —

Limiting the use of Mixins

Suppose if you want to prevent your mixin from being used on any class or you want to make you mixin class usable only for some class or its subclass it is basically you rely on some specific methods and field being already present.

For this, we only need to do only use “on” keyword.

So here in the example, as you can see that we have used on keyword to tell that it will only be used on reptile class and it will give access to its all functionality like Swim, Crawl and Bite mixins.

https://gist.github.com/shivanchalaeologic/8143db19617c9ee33c19081c7c59d717#file-mixindemo-dart

Conclusion :

So with this example, you can get the sense behind the mixins, it actually very useful in avoiding the code duplication without inheritance. Mixins can also be limited to work with any specific class and it makes it a powerful feature in the app development.

If this article has helped you a bit and found interesting please clap!👏

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Explore Dart String Interpolation

Related: Metadata Annotations in Dart

Related: Sum Of a List Of Numbers In Dart

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Adding AdMob to your Flutter App: Part 2

0

Before moving on to part 2, It is highly recommended to visit part 1 for setting up, Configuring & Initializing AdMob SDK —

Adding AdMob to your Flutter App
This blog guides you through adding an AdMob to an appmedium.com


What you’ll build :

✅How to use banner ads in a demo Flutter app

✅How to use interstitial ads in a Flutter app

✅How to use rewarded ads in a Flutter app


Contents :

Awesome Drawing Quiz App

Add a Banner Ad

Add an Interstitial Ad

Add a Rewarded Ad

Resources


Awesome Drawing Quiz

This blog will guide you through adding an AdMob banner, an interstitial ad, and a rewarded ad to an app called Awesome Drawing Quiz, a game that lets players guess the name of the drawing.

✔Important : This blog provides both starter code for this App as well as the complete project code with AdMobs.
Awesome Drawing App

You can find the 📂 starter code for this app without ad mobs over here —

flutter-devs/AdMobs-in-Flutter
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com


Add a Banner Ad in 4 steps !

In the previous blog we did a basic setup by adding Awesome Drawing Quiz firebase admob plugin & initialized the admob SDK . Now we will use that setup to add it into our demo Awesome Drawing Quiz App .

In this section, you add a banner ad at the top of the game screen, as shown —

Banner Ad

✔STEP 1 :

Open the lib/game_route.dart file, and import ad_manager.dart and firebase_admob.dart by adding the following lines:

lib/game_route.dart

...

// TODO: Import ad_manager.dart
import 'package:awesome_drawing_quiz/ad_manager.dart';

// TODO: Import firebase_admob.dart
import 'package:firebase_admob/firebase_admob.dart';

class GameRoute extends StatefulWidget {
...
}

✔STEP 2 :

Next, in the _GameRouteState class, add the following member and methods for the banner ad.

lib/game_route.dart

class _GameRouteState extends State<GameRoute> implements QuizEventListener {

...

// TODO: Add _bannerAd
BannerAd _bannerAd;

...

// TODO: Implement _loadBannerAd()
void _loadBannerAd() {
_bannerAd
..load()
..show(anchorType: AnchorType.top);
}

...
}

✔STEP 3 :

In the initState() method, create a BannerAd object, and load the banner ad. Note that the banner displays a 320×50 banner (AdSize.banner).

lib/game_route.dart

@override
void initState() {
...

// TODO: Initialize _bannerAd
_bannerAd = BannerAd(
adUnitId: AdManager.bannerAdUnitId,
size: AdSize.banner,
);

// TODO: Load a Banner Ad
_loadBannerAd();
}

✔STEP 4 :

Finally, release the resource associated with the BannerAd object by calling the BannerAd.dispose() method in the dispose() callback method.

lib/game_route.dart

@override
void dispose() {
// TODO: Dispose BannerAd object
_bannerAd?.dispose();

...

super.dispose();
}

That’s it! Run the project, to see a banner ad shown at the top of the game screen.

Banner Ad Added

Add an Interstitial Ad in 5 steps !

✔STEP 1 :

First, add the following members and methods for the interstitial ad in the _GameRouteState class.

lib/game_route.dart

https://gist.github.com/Anirudhk07/e04d17884fd2ecbbb619bf8ed30d4f62#file-game_route-dart

✔STEP 2 :

Next, initialize _isInterstitialAdReady and _interstitialAd in the initState() method. Because _onInterstitialAdEvent is configured as an ad event listener for _interstitialAd, every ad event from _interstitialAd is delivered to the _onInterstitialAdEvent method.

lib/game_route.dart

@override
void initState() {
...

// TODO: Initialize _isInterstitialAdReady
_isInterstitialAdReady = false;

// TODO: Initialize _interstitialAd
_interstitialAd = InterstitialAd(
adUnitId: AdManager.interstitialAdUnitId,
listener: _onInterstitialAdEvent,
);
}

In this code, an interstitial ad is displayed after a user completes 5 levels. To minimize unnecessary ad requests, we start loading an ad when a user reaches level 3.

✔STEP 3:

In the onNewLevel() method, add the following lines.

lib/game_route.dart

@override
void onNewLevel(int level, Drawing drawing, String clue) {
...

// TODO: Load an Interstitial Ad
if (level >= 3 && !_isInterstitialAdReady) {
_loadInterstitialAd();
}
}

When a game finishes, the game score dialog is displayed. When a user closes the dialog, it routes a user to the home screen of the Awesome Drawing Quiz.

Because interstitial ads should be displayed between screen transitions, we show the interstitial ad when a user clicks the CLOSE button.

✔STEP 4:

Modify the onGameOver() method as follows:

lib/game_route.dart

https://gist.github.com/Anirudhk07/620fab75db3f29cfd3437e5c2f3b0141#file-ad-dart

✔STEP 5:

Finally, release the resource associated with the InterstitialAd object by calling the InterstitialAd.dispose() method in the dispose() callback method.

lib/game_route.dart

@override
void dispose() {
...

// TODO: Dispose InterstitialAd object
_interstitialAd?.dispose();

...

super.dispose();
}

That’s it! Run the project to see an interstitial ad displayed after the game finishes.


Add a Rewarded Ad in 3 steps !

In this section, you add a rewarded ad which gives a user an additional hint as a reward.

✔STEP 1:

First, add the members and methods for the rewarded ad in the _GameRouteState class. Note that RewardedVideoAd is a singleton object, so you don’t need to have a member for managing the instance of the RewardedVideoAd class.

RewardedVideoAdEvent.rewarded is the most important ad event in a rewarded ad. It’s triggered when a user becomes eligible to receive a reward (for example., finished watching a video). In this code, RewardedVideoAdEvent.rewarded calls the QuizManager.instance.useHint() method which reveals one more character in the hint string.

Also, according to the ad event, RewardedVideoAdEvent.rewarded updates the UI by changing the value of _isRewardedAdReady. Note that _isRewardedAdReady reloads the ad when a user closes the ad, to make sure the ad is ready as early as possible.

lib/game_route.dart

https://gist.github.com/Anirudhk07/87c1484ae0d1f08b206b3848d6d55798#file-reward-dart

✔STEP 2 :

Next, allow users to watch a rewarded ad by clicking the floating action button. The button shows only if a user hasn’t used a hint at the current level and a rewarded ad is loaded.

Modify the _buildFloatingActionButton() method, as follows, to display the floating action button. Note that returning null hides the button from the screen.

lib/game_route.dart

Widget _buildFloatingActionButton() {
// TODO: Return a FloatingActionButton if a Rewarded Ad is available
return (!QuizManager.instance.isHintUsed && _isRewardedAdReady)
? FloatingActionButton.extended(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Need a hint?'),
content: Text('Watch an Ad to get a hint!'),
actions: <Widget>[
FlatButton(
child: Text('cancel'.toUpperCase()),
onPressed: () {
Navigator.pop(context);
},
),
FlatButton(
child: Text('ok'.toUpperCase()),
onPressed: () {
Navigator.pop(context);
RewardedVideoAd.instance.show();
},
),
],
);
},
);
},
label: Text('Hint'),
icon: Icon(Icons.card_giftcard),
)
: null;
}

✔STEP 3:

Finally, remove the rewarded ad event listener in the dispose() callback method.

lib/game_route.dart

@override
void dispose() {
...

// TODO: Remove Rewarded Ad event listener
RewardedVideoAd.instance.listener = null;

...

super.dispose();
}

That’s it! Run the project and watch a rewarded ad, to get an additional hint !


Congratulations ! You have now added all ads to your app ! If you missed something , you can find the completed code for this app in the 📂 complete folder.

Happy Fluttering !! ❤


Resources

firebase_admob | Flutter Package
A plugin for Flutter that supports loading and displaying banner, interstitial (full-screen), and rewarded video ads…pub.dev

flutter-devs/AdMobs-in-Flutter
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build…github.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Adding AdMob to your Flutter App

Related: Securing Your Flutter App By Adding SSL Pinning

Related: SMS Using Twilio In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

A Complete Guide to Build Your First Mobile App

0

Imagine, you woke up one fine day and you have an idea of an amazing app that can bring revolutionary changes, and you can see it clearly in your mind — you can picture it. You know that this app is going to solve a big problem for the users and you can see that people would like it too.

But if you haven’t built an app before and this is your first attempt, How Exactly are you gonna do it?

The ruthless Mobile App Development industry spares no-one with its cut-throat competition and building your own app in such a competitive environment can get really tough. There are so many things to take into consideration, that it gets very stressful to think clearly.

In this article, we will see a start to finish guide for building your mobile if you follow these steps in your plan. Let’s see what those are:

Identify The Purpose of the App

If you already have an idea for your app, that’s a great start. But to actually put that idea into reality requires clarity of the purpose. What are the mission and the purpose that the app is going to serve? What is that particular problem is the app going to solve? How is it going to make the lives of the users better?

Remember, all that starts well ends well! Define your goals early in the process to avoid chaos and any room for confusion.

Sketch Your Idea

You don’t need to be a professional artist to sketch out your app. By developing sketches you are laying the foundation for your future interface. In this step, you visually conceptualize the main features and the approximate layout and structure of your application.

You don’t need any specific tools to sketch your idea. You just need a pen and a paper and see your idea coming to life on paper.

List down all the features that you want in your app. I, personally, like to separate the features into two categories, ‘Must have’ and ‘Good to have’. List down the features that your app can’t do without under the ‘Must Have’ category. Other good features that are not crucial can come under the ‘’Good to have’ category.

Do Some Market Research

Before you jump into this market, do some research about it. Research who your competitors are, what are the new market trends around your idea. This research will give you an idea about your competitor’s strengths, weaknesses.

There are two types of market research you can do, that are the most helpful:

  • Finding out what mistakes your competitors are making or have made
  • Finding out if people are looking for an app like yours

You want to walk into the shoes of the customer, so to speak. Instead of assuming the needs and desires of the customers while sitting in your room in front of the laptop, go out and talk to the people.

Who is your app for? What are they like? How does your app impact a particular problem that users are struggling with? How are they currently solving that problem? What change do you, with your app, seek to make?

Sometimes, you build the app for yourself, and that’s alright. Do the market research just for the fun of it, to work on your craft. Don’t underestimate the importance of preparation, research, and insight, though!

Create Mockups Of Your App

It’s best to make mockups before you start to build the app. A mockup is a rough sketch of your app’s layout, user interfaces (UIs), and flow.

A mockup doesn’t include :

  • Detailed UI elements
  • Color schemes and effects
  • The precise placing of UI elements

A mock-up is a way of showing how your app looks without any unnecessary details. A mock is a functional and not an aesthetical approach to your app’s design.

A mockup should also describe the flow and interactions of your app. What happens when you tap on that button? How do you get from screen A to screen B? What is the navigation flow of your app?

Apart from creating your mockup, you need to create a storyboard for your app. It will work as a guideline for your app screens so that you will know about the connection between two individual screens and helps to track the user’s navigation.

There are a lot of mockups and wireframing tools available on the internet. I personally like to use Balsamiq. But other than that there are some more really good mockup tools like:

  • Proto.io
  • Moqups
  • InVision, and many more.

Develop a Prototype

After you’ve identified your approach of development, the next stage is developing a prototype. It is actually the process of taking your idea and turning it into an application with limited functionalities, it’s also called a minimum viable product (MVP). Choose the most basic features of the app and start prototyping them. The MVP allows the user to access and experience the app with tangible features rather than just visualizing or reading the product description.

The MVP is very useful in attracting investors, working with manufacturers, and finding licenses. You can also share the app with beta testers to get an idea about what needs to be changed to enhance user experience. You can find a number of prototyping tools online, the most popular ones are Balsamiq, Moqups, and HotGloo.

Start Designing Your App

Now that your app idea is taking shape, it’s time to start designing the application. Now is the time, where your designer’s job starts. He will now come up with a high-resolution version of what previously your mockups.

The design of the app includes pixel-perfect visual details, graphic effects, image assets, and sometimes even animations and motion design. It is crucial in this stage that you include the comments on the prototype given by the testers. After all, the app is going to be used by your target audience. Their experience on the app will drive you to the best User Interface.

Let’s Test Your Design

For the first time during the entire development process, you have the actual concept of your app in front of you. It helps to identify the bugs, crashes, and missing features.

To test your app, again there are so many online app testing platforms that can be helpful. Two of my personal favorites are MarvelApp and Framer. These platforms will allow you to import your screens, add links to test the flow and make the design clickable.

This process aims at creating an environment close to how the typical user works with your app.

Identify Your Development Approach — Native, Web or Hybrid

Selecting the right approach for developing your app is highly important. Ideally, the app development approach must be in accordance with the time and budget constraints.

Native

Native apps deliver the best user experience but also require significant time and skill to be developed. These apps are basically platform-specific (Android, iOS, Windows, etc.)and require expertise along with knowledge. Native apps take time to build and with an increase in time the cost of development increases.

Web

Web apps are quick and cheap ones to develop and can run on multiple platforms. These are developed using HTML5, CSS, and JavaScript code. These web apps are less powerful than native apps.

Hybrid

A hybrid approach is the latest and arguably the smartest approach to develop an app. This approach combines prebuilt native containers with on-the-fly web coding in order to achieve the best of both worlds. In this approach, the developer augments the web code with native languages to create unique features and access native APIs which are not yet available through JavaScript.

One of the best hybrid mobile app development technologies is Flutter. Backed by Google, Flutter has changed the way we build apps. It is the most cost-effective and efficient framework ever. If you’re building your app, build your app in Flutter. Highly Recommended.

Let’s build it

once your app’s design passes the usability test and you’ve decided your approach, it is time to give a proper structure to your dream project. This process covers the coding part and the actual realization of your application. The mobile app development stage incorporates multiple activities like establishing the appropriate development environment, developing different parts of the code, preliminary testing, and creating the mobile application that can be installed and tested.

Usually, there are three aspects of any app- back-end, APIs, and the app front-end. Development is usually done in stages and you can expect your developer to provide interim builds that you will be able to run on your device itself.

Back-end

Database and server-side objects become imperative for supporting functions of your mobile app by connecting to a network. Configurations and changes could be needed to support the desired mobile app functionality if you are using an existing backend platform. The server-side objects developed during this stage must be configured and tested with the other components of the app.

Application Programming Interface

An API is a set of practices, protocols, and tools for developing software applications. It specifies how software components interact. Additionally, this programming interface is used when programming GUI components.

Front-endanalysed

The front-end called “client-side” programming is what your app users interact with. It implements required structure, design, animation, and behavior that you can see on the screen when you open up the websites, web applications, or mobile apps.

Test & Improve

Running a code review process during development helps in making sure that there are no major bugs left at the end to solve. Once you have a visually appealing and fully functional application, it’s time your developer conducts a final test of usability with other colleagues. In this process, there may be bugs that were overlooked, but here your developer can apply the last tweaks to your product.

Let’s Make it Public — Release time!

After all the hard work that you’ve put into this project, it’s finally time to give your dream project a fly. Your app is all set to be released in the market.

Now, when it comes to app marketplaces, different market places have different policies when it comes to publishing a new app. For instance, Android doesn’t straightaway review a newly submitted app, they’ll pass it and you’ll be able to instantly add your app to play store. But in case of iOS, it’s completely different, Apple holds the right to review and approve/reject the app before it goes live. Which may take up to weeks time.\

So, always go through the different publishing policies, before you set your launch date.

Maintainance — The Most Crucial State

One of the most important aspects which are mostly ignored by the development agencies/companies as well as app owners is the post-development Support. There are numerous vendors in the market like Samsung, HTC, Motorola, Vivo, Nokia, etc. who have customized their android OS as per their needs. Apart from different customized android OS, they have separate hardware and display resolutions. And not just Android, even iOS platform also has different devices and display resolutions. This entire web of different Operating Systems makes it impossible to test the app on every other OS in real-time.

There are two ways the user will interact with the app, either online or offline. With different interactions, the app shows different behaviors and bugs. We use multiple crash reporting tools and regularly analyze the bugs to keep the app experience intact.

The first two months after the app deployment are the most crucial in terms of app sustainability. For that, we use multiple tools for bug collecting, reporting, and eventually resolving. This entire bug life-cycle ensures the app is not Error-prone after published.

Don’t Forget to Market Your App

Whether you have just released your app or your app has downloaded by many, you should never stop marketing the app. Mobile app marketing plays a very important role in making the app successful. Market it as soon as it is released so that it is not lost in the ocean of apps on app stores. You will know through the feedback whether the users liked the app or not.

FlutterDevs’Approach

Once you have an idea for implementation, the most important factor is to check it’s Technical and Economical feasibility.

In technical feasibility analysis, your concepts will be analyzed by our technical experts to check if it technically possible or if it has some challenges.

In economical feasibility, the project is analyzed for its budget. A lot of times the complexity of the project can increase the budget which should be kept in consideration and the client should know about this.

At FlutterDevs, our expert team members Do Free Technical and Economical Feasibility Interactions, so that the client knows about the product before investing their money.

We also have a team of expert analysts, who will analyze and compare your product/project with your direct competitors in the market and help you define a better value proposition of the project so that you stand out among the crowd.

At flutterDevs we have a huge experience in all the processes of application development like conceptualizing, developing, releasing, marketing, and maintenance of the app. We have a specialized team to handle each process.

If you have an app idea, we would love to hear it.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Cubit State Management Flutter

In flutter, state management is like a life support system where the whole App depends on, there are different state management techniques like Redux, MobX, bloc, flutter bloc, provider, and cubit. Actually Cubit is a cocktail of Flutter Bloc and Provider where we use some features of both techniques and In this article, we are going to learn how to use and implement Cubit, So before we go for its implementation firstly let’s have some cursory knowledge of it.

About Cubit :

Cubit is a lightweight state management solution. It is a subset of the bloc package that does not rely on events and instead uses methods to emit new states.

Every cubit requires an initial state which will be the state of the cubit before emit has been called. The current state of a cubit can be accessed via the state getter.

The cubit package is a collection of different packages for cubit such as cubit, flutter cubit, hydrated cubit, replay cubit, cubit test, and a cubit angular and all these have their own functionalities that they bring in the scenario.

In all these packages the main package cubit used if you have plain old dart project and want to use functionalities of cubit state management.

Flutter cubit

flutter cubit consists of all the functionalities of the main cubit package and also provides other different functionalities for different kinds of widgets and one important thing it also uses the functionalities of provider package.

Hydrated cubit

It persists and restores data in the hive database and you can get the data and read it out after you have restarted your application.

Replay cubit

It allows you to redo and undo certain states, for example, you if want to delete your data or want to retrieve it again.

Remaining two packages cubit test is used for testing the framework and cubit angular is used in the angular framework

“ However, All the packages are divided into different parts for the sake of Simplicity and Easiness but all are in the single Repository which makes it better in use for different purposes “

Implementation

  1. First, we add the dependencies in pubspec.yaml file
flutter_cubit: 
replay_cubit:
cubit_test:

you can add cubit packages(explained above) according to your need.

then we need to create a class that would extend cubit, as here in the given example we are creating a class CounterCubit which is extending the cubit package and it will notify the function when the state will be changed.

It works like provider class for changing state where emit() function notifies to the widget where we are changing states, same like changenotifier() does in provider

https://gist.github.com/shivanchalaeologic/b8abfbcf69a2f9c2195816b43296286e#file-counter_cubit-dart

In the next step, we create CubitObserverClass() (optional) where we can observe transitions in our app or changes in states. We only need to extend the CubitObserver package, Here in this above code snippet, there are two methods increment and decrement, In which we have used that emit function which will increase and decrease the count of the value which we have defined in super().

https://gist.github.com/shivanchalaeologic/caf120fd1189cdacaa8e7287f229699a#file-cubit_observer-dart

and in onTransition() method we can see responses of states as you can see in the given picture below

But you need to initialize cubit observer first, we initialize it in the main() function

https://gist.github.com/shivanchalaeologic/6fc5032c89341716fe30b90d03601941#file-cubit_initialize-dart

Now you need to route class with CubitProvider() and then you need to mention your cubit class,

if you have multiple classes then you can also use Multipovider, it is same as we use in provider package so if you are already acquainted with provider then you must not face any issue here

https://gist.github.com/shivanchalaeologic/527dd71afb9ad25756c14f67aea0cc45#file-material-dart

so till now, we have created classes form where we can change states and observe them but till now we have not accessed states so for accessing states in cubit we need to use CubitBuilder(), it is like StreamBuilder() and FutureBuilder() and also consists same implementation technique.

https://gist.github.com/shivanchalaeologic/0526295bfff85fd114862cd70804f873#file-home_screen-dart

Here in the above example, you can see we have wrapped our ListViewBuilder() by CubitBuilder() which will emit states when we will change it, as you can see states are being changed in FloatingActionButton() by calling increment and decrement functions mentioned in CounterCubit class.

Now are ready with Cubit State Management Technique, and you can see in the video how states of the list are changed

Conclusion

Cubit is a combination of the bloc and provider packages where you get riddance from events and rely on methods while you get ease in managing it as it helps to implement it with ease without any boilerplate code so till now it is one of the best combinations of the two state management techniques.

You can find the source code from here.

flutter-devs/cubit_state_management
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: GetX State Management In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.