Razorpay is a popular payment gateway in India that allows developers to integrate payment options into their apps easily. In this blog, we will learn how to integrate Razorpay in a Flutter app and manage the payment state using Bloc state management.
Prerequisites:
·
A basic knowledge of Flutter and Dart programming
·
A basic understanding of Bloc state management
·
A Razorpay account and API Key
Step 1: Create a new Flutter project
To create a new Flutter project, open Android Studio or Visual Studio
Code and go to the ‘File’ menu and select ‘New Flutter Project’. Select the
‘Flutter Application’ option and give a name to your project.
Step 2: Add the Razorpay Package
To add the Razorpay package, go to the ‘pubspec.yaml’ file in your
Flutter project and add the following dependency:
dependencies:
flutter:
sdk: flutter
razorpay_flutter: ^1.2.2
Step 3: Create a Bloc for Payment State Management
In this step, we will create a Bloc for payment state management. To
do this, we will create a new directory called ‘bloc’ and inside that
directory, we will create a new file called ‘payment_bloc.dart’. This file will
contain the Bloc class and events.
import
'dart:async';
class PaymentBloc {
final _stateController =
StreamController<PaymentState>();
Stream<PaymentState> get
state => _stateController.stream;
void dispose() {
_stateController.close();
}
void updateState(PaymentState
state) {
_stateController.sink.add(state);
}
void addOrder(Order order) {
_orderController.sink.add(order);
}
}
enum PaymentState {
IDLE,
LOADING,
SUCCESS,
ERROR,
}
class Order {
final int amount;
final String orderId;
Order({this.amount,
this.orderId});
}
final paymentBloc = PaymentBloc();
In the above code, we have created a Bloc class called ‘PaymentBloc’.
This class has a StreamController called ‘_stateController’. This
StreamController is responsible for managing the payment state. We have defined
an enumeration called ‘PaymentState’ that contains all the possible payment
states. We also have a class called ‘Order’ that contains the details of an
order.
Step 4: Integrate Razorpay in the Flutter app
In this step, we will integrate Razorpay in the Flutter app. To do
this, we will create a new screen called ‘PaymentScreen’ and inside this
screen, we will add the Razorpay widget.
import
'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:myapp/bloc/payment_bloc.dart';
class PaymentScreen extends StatefulWidget {
@override
_PaymentScreenState
createState()
=> _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
Razorpay _razorpay;
@override
void initState() {
super.initState();
_razorpay = Razorpay();
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
}
@override
void dispose() {
super.dispose();
_razorpay.clear();
}
void openCheckout() {
var options = { 'key': 'your_razorpay_key',
'amount': paymentBloc.state.amount,
'order_id': paymentBloc.state.orderId,
'name': 'My App',
'description': 'Payment for Order',
'prefill': {'contact': '', 'email': ''},
'external': { 'wallets': ['paytm'] }
};
_razorpay.open(options);
}
void _handlePaymentSuccess(PaymentSuccessResponse response) {
paymentBloc.updateState(PaymentState.SUCCESS);
}
void _handlePaymentError(PaymentFailureResponse response) {
paymentBloc.updateState(PaymentState.ERROR);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Payment Screen'),
),
body: StreamBuilder(
stream: paymentBloc.state,
initialData: PaymentState.IDLE,
builder: (context, snapshot) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text( 'Payment State: ${snapshot.data.toString().split('.').last}',
style: TextStyle(fontSize: 20), ),
SizedBox(height: 20),
RaisedButton( onPressed: () {
paymentBloc.updateState(PaymentState.LOADING);
openCheckout();
},
child: Text('Pay Now'),
),
],
),
);
},
),
);
}
}
In the above code, we have created a StatefulWidget called
‘PaymentScreen’. In the ‘initState’ method, we have initialized the Razorpay
object and added event listeners for payment success and payment error. The
‘openCheckout’ method opens the Razorpay checkout and takes the payment. We
have also created two event listeners, ‘_handlePaymentSuccess’ and ‘_handlePaymentError’,
which update the payment state based on the payment response. The ‘build’
method contains a StreamBuilder that listens to the payment state and displays
the payment state in the UI.
Step 5: Add Navigation to the Payment Screen
To add navigation to the payment screen, we will add a new screen
called ‘HomeScreen’
and navigate to it from the main screen. In the ‘HomeScreen’, we will
add a button to navigate to the ‘PaymentScreen’.
class
HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext
context) {
return Scaffold(
appBar: AppBar(
title: Text('Home
Screen'),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context)
=> PaymentScreen()),
);
},
child: Text('Go to
Payment Screen'),
),
),
);
}
}
In the above code, we have created a StatelessWidget called
‘HomeScreen’. The ‘build’ method contains a button that navigates to the
‘PaymentScreen’ when it is pressed.
Step 6: Update the Main Method
Finally, we will update the main method to show the ‘HomeScreen’ as
the initial screen.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext
context) {
return MaterialApp(
title: 'Razor Pay with
Bloc',
home: HomeScreen(),
);
}
}
In the above code, we have created a StatelessWidget called ‘MyApp’.
The ‘build’ method returns a MaterialApp that shows the ‘HomeScreen’ as the
initial screen.
And that’s it! With these simple steps, we have successfully
integrated Razorpay in flutter with Bloc state management. You can now run your
app and make a payment through Razorpay.
Conclusion
In this tutorial, we have learned how to integrate Razorpay in flutter
with Bloc state management. Bloc state management is a powerful and flexible
approach to manage the state of your flutter app. By using Bloc, you can
separate the business logic from the UI logic and make your code more
maintainable. Razorpay is a payment gateway that makes it easy to accept
payments in India. By integrating Razorpay with Bloc, you can manage the
payment state in a clean and organized manner.
I hope you have found this tutorial helpful. If you have any
questions, please leave a comment below. Happy coding!


0 Comments