Integrating Google Pay in Flutter with BLoC State Management
Google Pay is a popular digital wallet that allows users to make payments quickly and securely. With its growing popularity, it's crucial for any app to have the ability to integrate Google Pay for a seamless user experience.
Flutter is a powerful open-source
framework for building cross-platform mobile apps, and it has a rich set of
plugins and libraries to enhance the development process. In this blog, we'll
be discussing the integration of Google Pay in Flutter with BLoC (Business
Logic Component) state management.
BLoC is a state management technique that
uses streams to communicate between the UI and the business logic. It's a
popular pattern used in Flutter development, and it helps to maintain the state
of the application and ensures that the UI and the business logic are
decoupled.
Step 1: Setting up the environment
First, you'll need to set up the
development environment to integrate Google Pay in your Flutter app. This
requires you to create a project in the Google Developers Console, obtain the
API keys, and enable the Google Pay API. To set up the environment, follow
these steps:
1.
Go to the Google Developers
Console and create a new project.
2. Enable the Google Pay API for the project.
3. Go to the credentials section and create a new API key.
4. Note down the API key as you'll need it in the next steps.
Step 2: Installing the Google Pay Flutter
plugin
Once the environment is set up, you'll
need to install the Google Pay Flutter plugin in your project. The plugin makes
it easier to integrate Google Pay in your app and handle the payments securely.
To install the plugin, follow these steps:
1.
Add the following line in the
pubspec.yaml file of your project:
dependencies:
google_pay: ^0.0.1
2. Run flutter pub get in the terminal to install the plugin.
Step 3: Implementing BLoC
Next, you'll need to create a BLoC
(Business Logic Component) to handle the payment process. The BLoC is
responsible for processing the payment and updating the UI accordingly. To
implement the BLoC, follow these steps:
1.
Create a new dart file in your
project and name it payment_bloc.dart.
2. Import the bloc and flutter_bloc packages in the file.
import 'dart:async'; import
'package:bloc/bloc.dart';
import
'package:flutter_bloc/flutter_bloc.dart';
3. Create an event class that defines the different payment events, such
as making a payment or processing a payment.
class PaymentEvent {
final String paymentMethod;
PaymentEvent({this.paymentMethod});
}
4. Create a state class that defines the different payment states, such
as processing the payment, payment success, and payment failure.
class PaymentState {
final String status;
PaymentState({this.status});
}
5. Create the BLoC class and extend it from the Bloc class. The BLoC
class should have a mapEventToState function that maps the payment events to
the payment states.
class PaymentBloc extends
Bloc<PaymentEvent, PaymentState> {
@override
PaymentState get initialState =>
PaymentState(status: 'idle');
@override
Stream<PaymentState>
mapEventToState(PaymentEvent event) async* {
if (event.paymentMethod == 'Google Pay')
{
yield PaymentState(status: 'processing');
try {
//
Code to process Google Pay payment
yield PaymentState(status: 'success');
} catch (e) {
yield PaymentState(status: 'failure');
}
}
}
}
Step 4: Integrating Google Pay
Once the BLoC is implemented, you can
integrate Google Pay in your Flutter app. To integrate Google Pay, follow these
steps:
1.
Import the Google Pay Flutter
plugin in your main dart file.
import
'package:google_pay/google_pay.dart';
2. Create a function that will initialize Google Pay with your API key.
Future<void> initializeGooglePay()
async {
GooglePay.initialize(
environment: GooglePay.SANDBOX,
merchantIdentifier:
"YOUR_MERCHANT_IDENTIFIER",
merchantName:
"YOUR_MERCHANT_NAME",
apiKey: "YOUR_API_KEY",
);
}
3. Create a function that will make a Google Pay payment.
Future<void> makeGooglePayPayment()
async {
try {
var paymentData = await
GooglePay.makePayment(
price: "10.00",
currencyCode: "USD",
merchantIdentifier:
"YOUR_MERCHANT_IDENTIFIER",
merchantName:
"YOUR_MERCHANT_NAME",
);
print(paymentData.toJson());
} catch (e) {
print(e);
}
}
4. In the main widget of your app, wrap it with a BlocProvider that
provides the PaymentBloc.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => PaymentBloc(),
child: MaterialApp(
home: HomePage(),
),
);
}
}
5. In the HomePage widget, create a button that will trigger the Google
Pay payment. You can also use the BLoC to update the UI based on the payment
status.
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: <Widget>[
BlocBuilder<PaymentBloc,
PaymentState>(
builder: (context, state) {
if (state.status == 'processing') {
return CircularProgressIndicator();
}
else if (state.status == 'success') {
return Text('Payment Success');
}
else if (state.status == 'failure') {
return Text('Payment Failure');
}
else {
return RaisedButton( onPressed: () async
{
BlocProvider.of<PaymentBloc>(context).add(
PaymentEvent(paymentMethod: 'Google
Pay'), );
await makeGooglePayPayment();
},
child: Text('Pay with Google Pay'),
);
}
},
),
],
),
),
),
);
}
}
6. Finally, call the initializeGooglePay() function in the main method.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initializeGooglePay();
runApp(MyApp());
}
And that's it! With these simple steps,
you have successfully integrated Google Pay in your Flutter app with BLoC state
management. The BLoC provides a centralized and reusable way to manage the
payment state and update the UI accordingly.
Comments
Post a Comment