flutter native ads between listview at random position
Hi Guys, Welcome to Proto Coders Point, this Flutter Tutorial is on how to add flutter admob native ads in flutter app.
So to show native admob ads in our flutter project, we will make use of a external library called flutter_native_admob package. Using which you can easily show cusomized native ads in your flutter android & ios application.
Brief about flutter native admob package
A Plugin that makes 70% work of developer to show admob ads into flutter project.
By using this plugin you can integrate firebase native admob ad. This plugin supports both Android & iOS platform.
Please Note: This package is not yet configured with Null safety in flutter, so to use this package your flutter project must use envirnment sdk less then 2.12.0.
Just open any existing flutter project or create a new project in your favorite IDE. In my case, i am making use of Android Studio IDE to build flutter projects.
2. Add dependencies
In your project, open pubspec.yaml file & add the native ads dependencies under dependencies section.
dependencies:
flutter_native_admob: ^2.1.0+3 # this Line Version may change.
Note: This package is not yet updated with nullsafety feature so kindly check if your project environment sdk version is less then 2.12.0.
3. Platform prerequisite setup needed
Android Setup
Open Android Studio module in Android Studio
Right click on android folder of your flutter project,
[right click] android > Flutter > Open android module in android studio.
1. Adding google services classpath
open[project]/android/app/build.gradle file.
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.0' // add this google services 4.3.0
}
2. Apply the google services plugin
at the bottom of same build.gradle file add the google services plugin.
apply plugin: 'com.google.gms.google-services'
3. Add meta-data of admob App ID in Android-Manifest.xml
if required, show a toast message to user about failed to load ads.
type:
type of ads NativeAdmobType.full. NativeAdmobType.banner.
conrolller:
To Control nativeadmobWidget
option:
Customize ads styling for appearance.
In Options, NativeAdmobOptions there are various properties that you can use to customize your native ads appearance as per your flutter app UI. Check out pub.dev page for more.
snippet code of NativeAdmob Widget wrapped with container
Container(
height: 250,
child: NativeAdmob(
adUnitID: "ca-app-pub-3940256099942544/2247696110", //your ad unit id
loading: Center(child: CircularProgressIndicator()),
error: Text("Failed to load the ad"),
controller: _controller,
type: NativeAdmobType.full,
options: NativeAdmobOptions(
ratingColor: Colors.red,
showMediaContent: true,
callToActionStyle: NativeTextStyle(
color: Colors.red,
backgroundColor: Colors.black
),
headlineTextStyle: NativeTextStyle(
color: Colors.blue,
),
// Others ...
),
),
),
Flutter Native Ad Example
Load/show Admob Native Ads in listview.builder at random position β flutter
Complete Source Code.
main.dart
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_admob/flutter_native_admob.dart';
import 'package:flutter_native_admob/native_admob_controller.dart';
import 'package:flutter_native_admob/native_admob_options.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> images = ['images/img1.jpg','images/img2.jpg','images/img3.jpeg','images/img4.jpg','images/img5.jpg'];
List<Object> dataads;
@override
void initState() {
super.initState();
setState(() {
dataads = List.from(images);
for(int i = 0;i<2;i++){
var min = 1;
var rm = new Random();
//generate a random number from 2 to 4 (+ 1)
var rannumpos = min + rm.nextInt(4);
//and add the banner ad to particular index of arraylist
dataads.insert(rannumpos, nativeAdWidget());
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: dataads.length,itemBuilder: (context,index){
if(dataads[index] is String)
{
return Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: Image.asset(dataads[index])
);
}else{
return Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: dataads[index] as nativeAdWidget
);
}
}),
)
);
}
}
class nativeAdWidget extends StatelessWidget {
final _controller = NativeAdmobController();
@override
Widget build(BuildContext context) {
return NativeAdmob(
adUnitID: "ca-app-pub-3940256099942544/2247696110",
loading: Center(child: CircularProgressIndicator()),
error: Text("Failed to load the ad"),
controller: _controller,
type: NativeAdmobType.full,
options: NativeAdmobOptions(
ratingColor: Colors.red,
showMediaContent: true,
callToActionStyle: NativeTextStyle(
color: Colors.red,
backgroundColor: Colors.black
),
headlineTextStyle: NativeTextStyle(
color: Colors.blue,
),
// Others ...
),
);
}
}
Use this ad unit id in your flutter app to display ads in your apps.
Now, Letβs move to flutter project where you want to integrate admob ads and display ads to your app users.
How to integrate admob ads in flutter apps
1. Add dependency: Google_Mobile_Ads Package
In your flutter project open pubspec.yaml and in dependencies section add the google mobile ads package dependencies
dependencies:
google_mobile_ads: ^0.13.0 # version may change check it
ImportantNote: project configuration required to use above google mobile ads flutter ads package.
Flutter: 1.22.0 or higher.
Android: Android Studio version 3.2 or higher. Target SDK version or minSDKVersion 19 and higher. Set CompileSdkVersion 28 or higher. Android Gradle Plugin 4.1 or high.
2. Android Platform Setup
Admob provided App Id should be added in AndroidManifest.xml as meta-data tag inside Application Tag.
<application
android:label="flutter_app_simple"
android:icon="@mipmap/ic_launcher">
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/> // replace App id with your app id
</application>
Note: you need to replace App ID in android:value=β your app idβ;
3. iOS Platform Setup
Update Info.plist
In your flutter project, navigate to βios/Runner/Info.plistβ open it & at bottom before end of </dict> add the below key and string.
A GADApplicationIdentifierkey with string value of your admob App ID. A SKAdNetworkItems ey with google;βs SKANetwrkIdentifier value of skadnetwork.
4. Initialize theMobile Ads SDK
Before you actual load ads & display then to app users, you must call βMobileAds.instanceβ, which loads mobile ads SDK.
MobileAds.instance.initialize();
5. Create an instance object of Ad Eg: BannerAd
A BannerAd instance should be provided with adUnitID, AdSize, AdRequest and a BannerAdListener.
BannerAd bAd = new BannerAd(size: AdSize.banner, adUnitId: 'ca-app-pub-3940256099942544/6300978111', listener: BannerAdListener(
onAdClosed: (Ad ad){
print("Ad Closed");
},
onAdFailedToLoad: (Ad ad,LoadAdError error){
ad.dispose();
},
onAdLoaded: (Ad ad){
print('Ad Loaded');
},
onAdOpened: (Ad ad){
print('Ad opened');
}
), request: AdRequest());
In above replace with your own adUnitID.
Different Banner AdSize
AdSize.banner
320 x 50
AdSize.largeBanner
320 x 100
AdSize.mediumRectangle
320 x 250
AdSize.fullBanner
468 x 60
AdSize.leaderboard
728 x 90
6. Show ads β Banner ads to user
Then to load and display Admob Banner ads, you can make use of AdWidget.
AdWidget(
ad: bAd..load(),
key: UniqueKey(),
),
Here, In Ad property you need to pass the bannerAd we have created above.
Thus this will load banner ads in your flutter app, as shown in below screenshots.
Complete Source Code β Flutter Admob Monetize β Banner Ad
AdmobHelper.dart
import 'dart:io';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class AdmobHelper{
static String get bannerID => Platform.isAndroid ? 'ca-app-pub-3940256099942544/6300978111' : 'ca-app-pub-3940256099942544/6300978111';
static initialize(){
if(MobileAds.instance == null){
MobileAds.instance.initialize();
}
}
static BannerAd getBannerAd(){
BannerAd bAd = new BannerAd(size: AdSize.fullBanner, adUnitId: bannerID , listener: BannerAdListener(
onAdClosed: (Ad ad){
print("Ad Closed");
},
onAdFailedToLoad: (Ad ad,LoadAdError error){
ad.dispose();
},
onAdLoaded: (Ad ad){
print('Ad Loaded');
},
onAdOpened: (Ad ad){
print('Ad opened');
}
), request: AdRequest());
return bAd;
}
}
main.dart β Only Banner ads at bottom of the screen
Video Tutorial on Monitizing flutter app with google admob β Banner Ad at bottom
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialize();
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 Admob ad example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomepage(),
);
}
}
class MyHomepage extends StatefulWidget {
@override
_MyHomepageState createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Admob Banner Test Ads'),
),
bottomNavigationBar: Container(
child: AdWidget(
ad: AdmobHelper.getBannerAd()..load(),
key: UniqueKey(),
),
height: 50,
),
);
}
}
Hurry! We are all set, If the test ads are working, Real-Time abs will show into your flutter application once you publish the app into AppStore, you can sit back and relax.π.
Showing admob banner ads randomly in between listview builder
Video tutorial on flutter listview ads
Source Code
AdmobHelper.dart
import 'package:google_mobile_ads/google_mobile_ads.dart';
class AdmobHelper {
static String get bannerUnit => 'ca-app-pub-3940256099942544/6300978111';
static initialization(){
if(MobileAds.instance == null)
{
MobileAds.instance.initialize();
}
}
static BannerAd getBannerAd(){
BannerAd bAd = new BannerAd(size: AdSize.fullBanner, adUnitId: 'ca-app-pub-3940256099942544/6300978111' , listener: BannerAdListener(
onAdClosed: (Ad ad){
print("Ad Closed");
},
onAdFailedToLoad: (Ad ad,LoadAdError error){
ad.dispose();
},
onAdLoaded: (Ad ad){
print('Ad Loaded');
},
onAdOpened: (Ad ad){
print('Ad opened');
}
), request: AdRequest());
return bAd;
}
}
main.dart
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialization();
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 Admob ad example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomepage(),
);
}
}
class MyHomepage extends StatefulWidget {
@override
_MyHomepageState createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
late List<String> datas; // late for null safty
late List<Object> dataads; // will store both data + banner ads
@override
void initState() {
// TODO: implement initState
super.initState();
datas = [];
//generate array list of string
for(int i = 1; i <= 20; i++){
datas.add("List Item $i");
}
dataads = List.from(datas);
// insert admob banner object in between the array list
for(int i =0 ; i<=2; i ++){
var min = 1;
var rm = new Random();
//generate a random number from 2 to 18 (+ 1)
var rannumpos = min + rm.nextInt(18);
//and add the banner ad to particular index of arraylist
dataads.insert(rannumpos, AdmobHelper.getBannerAd()..load());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: dataads.length,
itemBuilder: (context,index){
//id dataads[index] is string show listtile with item in it
if(dataads[index] is String)
{
return ListTile(
title: Text(dataads[index].toString()),
leading: Icon(Icons.exit_to_app),
trailing: Icon(Icons.ice_skating),
);
}else{
// if dataads[index] is object (ads) then show container with adWidget
final Container adcontent = Container(
child: AdWidget(
ad: dataads[index] as BannerAd,
key: UniqueKey(),
),
height: 50,
);
return adcontent;
}
}),
bottomNavigationBar: Container(
child: AdWidget(
ad:AdmobHelper.getBannerAd()..load(),
key: UniqueKey(),
),
height: 50,
),
);
}
}
Output
How to show Interstitial ads in flutter app
Video Tutorial
Load Interstitial ad
To Load an InterstitialAd you need to pass some parameters those are adUnitId, an AdRequest(), and an adLoadCallback:InterstitialAdLoadCallback(β¦..).
Below is an snippet code to load admob Interstitial Ads in flutter
InterstitialAd.load(
adUnitId: 'ca-app-pub-3940256099942544/1033173712', // replace with your Admob Interstitial ad Unit ID
request: AdRequest(),
adLoadCallback:InterstitialAdLoadCallback(
onAdLoaded: (InterstitialAd ad){
_interstitialAd = ad;
},
onAdFailedToLoad: (LoadAdError error){
print('InterstitialAd failed to load: $error');
}),
);
Ad Event Tracking
To track your ad unit, you can use FullScreenContentCallback, by using which you easily keep track of ads lifecycle, such as when the ad is shown or if user dismissed the ad that is shown.
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialization();
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 Admob ad example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomepage(),
);
}
}
class MyHomepage extends StatefulWidget {
@override
_MyHomepageState createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
late List<String> datas; // late for null safty
late List<Object> dataads; // will store both data + banner ads
AdmobHelper admobHelper = new AdmobHelper(); // object to access methods of AdmobHelper class
@override
void initState() {
// TODO: implement initState
super.initState();
datas = [];
//generate array list of string
for(int i = 1; i <= 20; i++){
datas.add("List Item $i");
}
dataads = List.from(datas);
// insert admob banner object in between the array list
for(int i =0 ; i<=2; i ++){
var min = 1;
var rm = new Random();
//generate a random number from 2 to 18 (+ 1)
var rannumpos = min + rm.nextInt(18);
//and add the banner ad to particular index of arraylist
dataads.insert(rannumpos, AdmobHelper.getBannerAd()..load());
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: dataads.length,
itemBuilder: (context,index){
//id dataads[index] is string show listtile with item in it
if(dataads[index] is String)
{
return ListTile(
title: Text(dataads[index].toString()),
leading: Icon(Icons.exit_to_app),
trailing: Icon(Icons.ice_skating),
onTap: (){
admobHelper.createInterad(); // call create Interstitial ads
},
onLongPress: (){
admobHelper.showInterad(); // call show Interstitial ads
},
);
}else{
// if dataads[index] is object (ads) then show container with adWidget
final Container adcontent = Container(
child: AdWidget(
ad: dataads[index] as BannerAd,
key: UniqueKey(),
),
height: 50,
);
return adcontent;
}
}),
bottomNavigationBar: Container(
child: AdWidget(
ad:AdmobHelper.getBannerAd()..load(),
key: UniqueKey(),
),
height: 50,
),
);
}
}
RewardedAds in Flutter
Load RewardedAd
To Load an RewardedAd you need to pass some parameters those areΒ adUnitId, anΒ AdRequest(), and anΒ rewardedadLoadCallback:RewardedAdLoadCallback(β¦..).
Below is an snippet code to load admob Rewarded Ads in flutter
RewardedAd.load(
adUnitId: 'ca-app-pub-3940256099942544/5224354917',
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print('$ad loaded.');
// Keep a reference to the ad so you can show it later.
this._rewardedAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
},
));
RewardedAd Event Tracking
To track your ad unit, you can use FullScreenContentCallback, by using which you easily keep track of ads lifecycle, such as when the ad is shown or if user dismissed the ad that is shown.
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_simple/AdmobHelper.dart';
import 'package:flutter_app_simple/RewardAdsExample.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
AdmobHelper.initialization();
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 Admob ad example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: RewardAdsExample(),
);
}
}
How much does AdMob pay per 1000 impression?
Banner ads will give you very little revenue per 1000 impressions you can only earn about $0.50, but as you all know that google Admob pays only when ads are been clicked. some time with 1000 impression a day you can earn more than $2.00 with almost 5 -10 click( all depends on the location of the ads we clicked), if an app user from the USA clicks on your ads then you can easily earn around $0.30 β $1.00 per ad click, but with another country, it will be less most of the time.
while with native big ads will pay you around $1 dollor per 1000 impression.
Google Admob is an ad network platform for mobile ads by which you can monetize your android & ios application. Google Admob makes earn revenue easy with in-app ads, i.e. easy-to-use monetization platform to grow you app business.
You need to create a new Admob account or just sign In into your existing google admob account.
Fill all the details while creating new account like country, time zone, billing currency detail as shown in below screenshot & accept the adsense team & condition.
2. Add your first app with admob
Then once you have created account with admob, now you can add your first app in admob console.
If your account is new you will see option to add your first app.
else goto App section in drawer & add app
Add a new app and give a name related to your app.
3. Select platform β Monitize with admob
Now select platform either Android or iOS as per you app built.
If your app is listed in playstore or appstore select yes or no
If app is listed in play store or App store
If your Android or iOS app is already listed in playstore or app store, you need to give URL or package name of your app.
4. Create A Ad Unit
Select your desired ad unit like Banner ads, intertitial ads, rewarded ads, Native ads etc.
Next
Select the Ad Style Unit, i selected banner ads as you see in below screenshot.
Give a name to your ad unit and create ad unit
5. Done β Admob app is created with ad unit
Done, Therefore, now our app is connected with admob & ready to show ads on your app.
How to add admob to android app or iOS app.
* Now you just need to place your ads unit in your app code to load and display ads on your mobile app.
** will soon post a article on how to add admob to android app (flutter)
Bank Account program in java using classes & object
A java program for student to learn a simple bank account program in java using classes and object. A menu-driven java bank account code where a user can log in, Deposit Amount, Withdraw amount & check account balance, with proper customized Exception Handling.
Bank Account Java Program β Menu Driven Program
Here is my Java Project Structure, for better understanding the Process
Project File Structure
So as we are going to develop a project for bank transaction,( a bank account program in java using classes & object).
Here is source code on java bank account program
App.java
This is starting point of your java code i.e. main(). From here we are just creating an object of Banking class and by using the object i.e. b we are calling initiate() method of Banking class.
public class App {
public static void main(String[] args) throws Exception {
System.out.println("Hello, World!");
Banking b = new Banking();
b.initiate();
}
}
Banking.java
In Banking class we have a int varible amount that is set to 1000 initially,
Banking class can perform various task such a Login, Get Balance, Deposit (add amount), Withdrawal available money, with proper exception handling, So for all this task, i have created the method as below.
initiate() β used to login, it calls Login class for further process.
getBalance() β it return available bank account balance.
add(amt) β deposit the amount or update the balance(amount)
withdrw(amt) β remove the amount from balance amount from bank account.
import java.util.Scanner;
class Banking{
int amount = 1000;
public void initiate()
{
Login login = new Login();
try{
login.acceptInput();
login.verify();
}catch(Exception e)
{
try{
login.acceptInput();
login.verify();
}catch(Exception f)
{
}
}
}
public int getBalance(){
return amount;
}
public void add(int amt){
amount = amount + amt;
System.out.println("Amount deposited Successfully");
System.out.println(" ");
System.out.println("Total Balance: " +amount);
System.out.println(" ");
}
public void withdrw(int amt){
System.out.println(" ");
if(amount < amt)
{
InvalidBankTransaction invalidWithDraw = new InvalidBankTransaction("InValid Withdrawal Amount");
System.out.println(invalidWithDraw.getMessage());
}else{
amount = (amount - amt);
System.out.println("Please Collect your " + amt +" Rupees");
System.out.println(" ");
System.out.println("Total Balance: " +amount);
System.out.println(" ");
}
}
}
Login.java
To get Logged in i have a fixed ac number =1234 and ac password=9999, using which a use can login,
Login class has 2 method:
acceptInput() β used to ask n take input from user.
verify() β used to check if the login was successful or not successful. if successful then use the banking class to fetch balance and then show a menu-driven option to the user to select the menu. if login do failed then show a proper message to a user by using the InvalidBankTransaction Customized Exception class.
import java.util.Scanner;
class Login{
int ac_number = 1234;
int ac_pass = 9999;
int ac;
int pw;
public void acceptInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the account number:");
ac = scanner.nextInt();
System.out.println("Enter the Password:");
pw = scanner.nextInt();
}
public void verify() throws Exception{
if(ac == ac_number && pw == ac_pass)
{
System.out.println("Login Successfull!");
Banking banking = new Banking();
System.out.println(" ");
System.out.println("Your Balance is: "+banking.getBalance()+" Rupees");
System.out.println(" ");
Menu menu = new Menu();
menu.showMenu();
}else{
InvalidBankTransaction loginfailed = new InvalidBankTransaction("Incorrect login credentials");
System.out.println(loginfailed.getMessage());
throw loginfailed;
}
}
}
Menu.java
The java program is an example of a menu-driven program, using Menu class we are showing the menu option to the user.
Here we are showing menu item to the user and there is a swtich statement to go with the option selected by the user
For Example, we have 1 for Deposit, so when the user select 1 option then the deposit process executes likewise 2 and 3 are for withdrawal & check balance respectively.
import java.util.Scanner;
class Menu{
int selectedOption;
Banking banking = new Banking();
public void showMenu()
{
System.out.println("Please Select an option below:");
System.out.println("Press 1 to Deposit Amount.");
System.out.println("Press 2 to Withdraw Amount.");
System.out.println("Press 3 to View Balance");
System.out.println("Press any key to Exit");
System.out.println(" ");
Scanner scanner = new Scanner(System.in);
System.out.println ("Press any key:");
selectedOption = scanner.nextInt();
switch (selectedOption) {
case 1:
Deposit d = new Deposit();
int depamt = d.userInput();
banking.add(depamt);
showMenu();
break;
case 2:
System.out.println("Please Enter the amount to withdraw:");
int withamt=scanner.nextInt();
banking.withdrw(withamt);
showMenu();
break;
case 3:
System.out.println("Your Account Balance is "+banking.getBalance()+" Rupees");
System.out.println(" ");
showMenu();
break;
default:
System.out.println("Transaction Ended");
System.exit(0);
break;
}
}
}
Deposit.java
When user select option 1 from menu Deposit class is been called where user is asked to enter the amount to be deposited.
Here is a check statement where if user enter negative amount then show a proper message using Exception Class.
If user enter currect amount then userInput() method will return the amt back to itβs object from where it was called.
import java.util.Scanner;
class Deposit{
int amt= 0;
public int userInput()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the amount to be deposited: ");
amt = scanner.nextInt();
if(amt<=0)
{
InvalidBankTransaction depositnegativeError = new InvalidBankTransaction("Invalid Deposit Amount");
System.out.println(depositnegativeError.getMessage());
userInput();
}else{
return amt;
}
return amt;
}
}
InvalidBankTransaction.java
So this is common Customized Exception class used to handle all the user errors.
class InvalidBankTransaction extends Exception
{
String errorMessage;
public InvalidBankTransaction(String message)
{
errorMessage = message;
}
public String getMessage()
{
return errorMessage;
}
}
Output β Result of above java code for bank operation
Best App Development Tools for Flutter development
Hi Guys, Welcome to Proto Coders Point, In this Blog Post letβs discuss on best app development tools/kits for app build with flutter.
Below I have made a list of the most effective flutter app development tools, which you can check out, learn about it and use right now for developing the best cross-platform flutter app & user-friendly UI applications. So letβs not waste time and check out the list of best Flutter development tools β App development kits.
The Android Studio IDE Tool is the top best flutter software development tools, This tool comes with feature like editing support, syntax highlighting, Intelligent code Editor and also an APK analyzer that you can use to check the size of a flutter app & reduce the size of the app. IDE that enables you to develop an effective, responsive and rich flutter app, Android Studio is the best app building tool & UI design tools.
Visual Studio IDE is mostly used for developing Web Application but currently, Visual Studio is rapidly growing in Flutter development, Developers are using VSCode to build cross-platform app development like React Native & Flutter app.
VSCode is been developed by Microsoft and itβs a free & open-source code editor tool that is available for Windows, Linux & Mac OS.
VSCode is easy & simple to use and app build with flutter. Download VSCode
Supernova is a designing took used to create a beautiful UI code. recently supernova team has added support for the flutter platform too,
By Using supernava it is feasible to create flutter app using supernova and make modification to your flutter app in real-time.
The Best thing so supernova is it allows you to use Adobe XD UI or Sketch just by importing it here. Supernova promises you a flexible automation platform.
5. Adobe Plugin
Adobe XD has created a new plugin for flutter UI Development. This Flutter Adobe Plugin convert your mobile app designs into a flutter widget code, provide you with a .dart file that you can easily place in your flutter codebase.
Every app that is been developed will have some kind of hidden bugs that not even the developer or tester detect during the testing phase. You can use a tool called Instabug, it provides real-time contextual insights into your mobile application.
Flutter Developers use Instabug for bug reposting, in-app crash reporting, conducting a survey or ask your app users a new feature requirement request.
You can easily integrate instabugs flutter SDK in your flutter project and turn on real-time bug reposting and analysis your app usage.
RevenueCat is very useful when you want to integrate in-app purchase or add a monthly subscription plan for your premium users. basically, RevenueCat is a purchase or subscription management tool. You can install Revenue Purchase SDK in your flutter project and easily manage your app business.
This also support in Android, iOS and many other platform where you want to integrate in-app purchase.
Itβs an Open source analytic tools, Count.ly allows you to monitor your audience, and check all the analytics of how your app is performing, with this tool, you can track your app KPIs metric and check out how your apps are growing. They also provide you with a paid version using which you can send a push notification, extra feature flags, as well an A/B testing Feature.
Run the native mobile app in your browser itself. Appetize is a cross-platform mobile app development took that allows you to run native app in any browser in HTML or JavaScript format. Appetize is used for streamline app demos, customer support, training, testing and more.
more over this tools will reduce time-to-market and lauch apps faster.
A Firebase is a cross-platform solution a platform service provided by Google. Firebase is a very useful tool that you can integrate into your flutter project.
By using firebase you can build a complete back end API. This also provides real-time database, cloud database, ML function, firebase push notification, firebase cloud messaging, crash reposting, analytic and many more.
Conclusion
With the list of best app development tools, you can make your flutter app development project faster and in efficient way.
How to disable or make button invisible in flutter
Hi, Guys Welcome to Proto Coders Point, In this fluter tutorial we will learn how to disable a button in flutter & also learn how to make flutter raisedbutton invisibility when not in use so that we can prevent a button from being clicked twice accidentally.
Preventing a button from being clicked twice accidentally
Sometimes what happens is when a user wants to submit a form or perform an action when a button is clicked but accidentally a submit button or flutter raisedbutton gets clicked twice, due to flutter button getting clicked double-time accidentally, double data entry get stored or user perform task twice or face some problem while using your flutter app.
So to prevent this you need to disable further onClick event on button, until the task or the process get completed.
How to enable/disable a button in a flutter β OnClick disable button
Step to follow to enable/disable a button in flutter app.
Video Tutorial
1. Create a boolean variable isButtonClickable
Under StatefullWidget create a boolean variable that we can use to check if button is disabled or enabled.
bool isButtonClickable = true;
initially, as per your app requirement you can keep it either to true or false, in my case i am keep it to true.
2. Create a flutter button ( ElevatedButton) with onPressed property
In the below Snippet Widget Button Code, Depending on the value of isButtonClickable, I am setting text to button either Clickable or Not Clickable,
Then in onPressed() i am using if statement to check if button is Enabled, if Enabled then call the method to perform action/task else do nothing.
3. Create a method/function which perform some task.
Then, when a button is pressed, the method/function is called, in which by using Flutter State Management (setState()), I am updating isButtonClickable to false, Which make button disable.
That means now user will not be able to click button again twice by mistake.
NOTE: Just, for Example, I am using Future.delayed to make isButtonClickable = true after certain duration (seconds), so that it can be clickable after some time.
In your case as per your project, you can perform an action like, for example, a data is getting submitted to the database & depending on server response (success) you can clean the form and enable button or simply navigate the user to another flutter page.
void ButtonClicked() async {
Duration time = Duration(seconds: 5);
setState(() {
isButtonClickable = false; //make the button disable to making variable false.
print("Clicked Once");
Future.delayed(time,(){
setState(() {
isButtonClickable = true; //future delayed to change the button back to clickable
});
});
});
}
4. [Optional] Make Button Invisible
If you want to make the button invisible, until any task or process is getting performed you can simply wrap the ElevatedButton Widget with the Visibility widget and use the visible property & set it to true or false.