Add two in Function to a button Flutter - flutter

how can I add two function to a single button?
I have a button that sends a request to a server and I would like to add a Dialog after sending the request... I tried this:
onPressed: () {
_makePostRequest();
showAlertDialog(context);
},
But still not working...
The post code:
_makePostRequest() async {
final url = Uri.parse('http://127.0.0.1/API');
final headers = {"Content-type": "application/json"};
final json = '{"id": "1", "status": "1"}';
final response = await post(url, headers: headers, body: json);
final statusCode = response.statusCode;
final body = response.body;
}
The Show Dialog code:
void showAlertDialog(BuildContext context) {
Widget okButton = TextButton(
child: Text("OK"),
onPressed: () {},
);
AlertDialog alert = AlertDialog(
title: Text("PMZ Label Print"),
content: Text("Label is printing..."),
actions: [
okButton,
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}

Try to below code
Your Button
onPressed:(){
_makePostRequest();
}
Your API Call
_makePostRequest() async {
final url = Uri.parse('http://127.0.0.1/API');
final headers = {"Content-type": "application/json"};
final json = '{"id": "1", "status": "1"}';
final response = await post(url, headers: headers, body: json);
final statusCode = response.statusCode;
final body = response.body;
//your alert function call
if (response.statusCode == 200) {
showAlertDialog(context);
} else {
print(
"Error",
);
}
}
I have try above code and my code is working

you just need to add async on onPressed.
onPressed: ()async {
await _makePostRequest();
showAlertDialog(context);
},

_makePostRequest is of type Future so you can use 2 ways :
First one:
onPress:(){
_makePostRequest().then((v){
showAlertDialog(context);
});
}
Second one:
onPress:()await {
await YourFunction();
showAlertDialog(context);
}

Related

call parameter function to get data in flutter

I'm learning and trying to add parameters when calling parameters in functions when getting data from the API, but I'm a bit confused about how I call them in widgets.
static Future<Map<String, DataKuliahModel>> getDataKuliah(String smt) async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
await Future.delayed(const Duration(milliseconds: 1000));
// String responseJson = await rootBundle.loadString('assets/1.json');
Map<String, DataKuliahModel> finalResult = {};
final response = await http.get(
Uri.parse(
'$url/auth/mhs_siakad/perwalian/get_paket',
),
headers: {
'Authorization': 'Bearer $token',
},
);
final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
result.forEach((key, value) {
DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
finalResult.addAll({
key: dataKuliah,
});
});
return finalResult;
}
and I want to call him here
When you declare a function with positional parameters you need to provide those parameters when you call that function.
import 'package:flutter/material.dart';
class Services {
static Future<String> greeting(String name) async {
/// this function doesn't need to be Future
/// but when you call API to get some data it should be a Future
return 'Hello $name';
}
}
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
#override
Widget build(BuildContext context) {
return FutureBuilder(
/// pass positional parameter to [greeting] here
future: Services.greeting('Dash'),
builder: (context, AsyncSnapshot<String> snapshot) {
return Center(
child: Text(snapshot.data ?? 'default'),
);
},
);
}
}
Result: Hello Dash
In your case smt seems to be an int not a String
and you have to pass it as query parameter to http request as follows
static Future<Map<String, DataKuliahModel>> getDataKuliah(int smt) async {
String url = Constant.baseURL;
String token = await UtilSharedPreferences.getToken();
await Future.delayed(const Duration(milliseconds: 1000));
// String responseJson = await rootBundle.loadString('assets/1.json');
Map<String, DataKuliahModel> finalResult = {};
final response = await http.get(
// Uri.parse(
// '$url/auth/mhs_siakad/perwalian/get_paket',
// ),
Uri.http(url, '/auth/mhs_siakad/perwalian/get_paket',
{'smt':smt}),
headers: {
'Authorization': 'Bearer $token',
},
);
final result = jsonDecode(response.body)['data'] as Map<String, dynamic>;
result.forEach((key, value) {
DataKuliahModel dataKuliah = DataKuliahModel.fromMap(value);
finalResult.addAll({
key: dataKuliah,
});
});
return finalResult;
}
Have you looked at the Uri replace method?
You can do the following:
Uri.parse('$url/auth/mhs_siakad/perwalian/get_paket').replace(queryParameters:{ "smt":"$smt"});
Update on FutureBuilder:
// Put this outside your build function
Future<Map<String, DataKuliahModel>> DK ;
// Put this in your initState if you want the future to run on page load or use it for events like onTap
DK = Service.getDataKuliah(<PARAM>);
// This is in your build method
FutureBuilder(
future:DK,
builder: (context, snapshot) {
// add wigets to display results here
}
)

How to do a Razorpay integration in Flutter

I am able to deploy payment transaction but the server part is very hard. How can I create a orderid and how can we find the payment is done by a specific user?
Hope you set up all the necessary things.
Step 1: creating Order using Razorpay official Order Api:
void createOrder() async {
String username = 'xxxxxxxxxx';// razorpay pay key
String password = "xxxxxxxxxxxxxxxx";// razoepay secret key
String basicAuth =
'Basic ${base64Encode(utf8.encode('$username:$password'))}';
Map<String, dynamic> body = {
"amount": 1 * 100,
"currency": "INR",
"receipt": "rcptid_11"
};
var res = await http.post(
Uri.https(
"api.razorpay.com", "v1/orders"), //https://api.razorpay.com/v1/orders // Api provided by Razorpay Official 💙
headers: <String, String>{
"Content-Type": "application/json",
'authorization': basicAuth,
},
body: jsonEncode(body),
);
if (res.statusCode == 200) {
openCheckout(jsonDecode(res.body)['id']); // 😎🔥
}
print(res.body);
}
//*#################################################################
Step 2: Open Razorpay checkout interface.
After getting orderId from Razorpay official Api, pass the id when calling openCheckout(jsonDecode(res.body)['id']); function
void openCheckout(String orderId) async {
var options = {
'key': 'xxxxxxxxxxxxxxxx',
"amount": 1 * 100,
'order_id': orderId,
'name': 'main.co.in',
// 'prefill': {'contact': '', 'email': 'test#razorpay.com'},
'external': {
'wallets': ['paytm']
}
};
try {
razorpay.open(options);
} catch (e) {
debugPrint('Error: e');
}
}
3rd Step: Signature verification.
This is important if you automatically wanna transfer your amount to your bank account.
for Hmac SHA key , install this package: crypto:
handlerPaymentSuccess(PaymentSuccessResponse response) {
final key = utf8.encode('NgDLPyiDRPuQpcXy1E3GKTDv');
final bytes = utf8.encode('${response.orderId}|${response.paymentId}');
final hmacSha256 = Hmac(sha256, key);
final generatedSignature = hmacSha256.convert(bytes);
if (generatedSignature.toString() == response.signature) {
log("Payment was successful!");
//Handle what to do after a successful payment.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success : payment successful"),
// content: const Text("Are you sure you wish to delete this item?"),
actions: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(true);
// PlaceOrderPrepaid();
},
child: Text("OK"))
// ),
],
);
},
);
} else {
log("The payment was unauthentic!");
}
}

How to access response code and body by calling a method returning http.Response?

I use the following class (a separate dart file) to provide API services:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Services {
static Future<http.Response> login(String username, String password) async {
var url = "https://10.0.2.2:5001/api/Login/LoginSystem";
Map data = {"Username": username, "Password": password};
var body = json.encode(data);
var response = await http.post(Uri.parse(url),
headers: {
"content-type": "application/json",
"accept": "application/json"
},
body: body);
print(response.statusCode);
print(response.body);
return response;
}
}
And I use the following code to call the service function:
onPressed: () {
var response = Services.login("fa2020", "123");
if (response.statusCode == 200) {
showDialog<String>(
context: context,
builder: (BuildContext context) =>
const AlertDialog(
title: Text("ALert"),
content: Text(response.body),
));
}
}
My problem is that I cannot access the response.statusCode and response.body in the last code. How can I fix it?
Use async-await in onPressed callback as Service.login executes in async manner.
onPressed: () async {
var response = await Services.login("fa2020", "123");
// ...
},

How do I store an integer correctly in the SharedPrefences in Flutter without getting a null?

I want to save an Int which I can reuse in a new class. For this I used SharedPreferences. The problem is when I want to open the Int on my new page then I get only a null out.
But I noticed that when I do a hot restart and then switch to the page no null comes out but what I saved before. Where is my error?
Here I save the value:
Future<Album> fetchAlbum() async {
int msgId;
//I fetch json from a page and store the value at msgId. I just don't have it in my code sample in here
SharedPreferences prefs = await SharedPreferences.getInstance();
msgId = (prefs.getInt('msgId'));
msgId = (prefs.getInt('msgId') ?? jsonData[0]["msgId"]);
prefs.setInt('msgId', msgId);
}
Here I retrieve the saved value (on a new page):
String url ='MyUrl';
int msgId;
// int intMsgId;
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
msgId = (prefs.getInt('msgId'));
prefs.setInt('msgId', msgId);
print(msgId);
});
}
Future<String> makeRequest(String text) async {
_loadCounter();
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
msgId = (prefs.getInt('msgId'));
prefs.setInt('msgId', msgId);
print(msgId);
});
print("------MSG_ID------");
print(msgId);
print("------MSG_ID------");
//print(msgId.length);
if (msgId != null) {
var response = await http.post(Uri.encodeFull(url),
headers: {
"x-requested-with": "xmlhttprequest",
"Accept": "application/json",
"content-type": "application/json",
},
body: jsonEncode({
"messages": {
"msgId": msgId,
"refId": msgId
}
}));
print(response.body);
}
}
The problem probably because you don't await the SharedPreferences.setInt method.
your code:
prefs.setInt('msgId', msgId);
change to:
await prefs.setInt('msgId', msgId);
because SharedPreferences.setInt is async.
In your case, I would do this:
// other UI code
child: FutureBuilder(
future: prefs.getInt('msgId'), // your future
builder: (context, snapshot) {
if (snapshot.hasData) {
return Center(child: Container(child: Text('data: ${snapshot.data}')));
} else {
// We can show the loading view until the data comes back.
return CircularProgressIndicator();
}
},
),

How to do stream builder to get data from bloc in flutter

I am new in BLOC and I am trying to read respond from api.. but whenever I call stream builder... my widget always stops in wait... here is my code
here is api provider file
class Provider {
final _url = '...';
Future<List<LoginRespon>> login(a, b) async {
List<LoginRespon> datalogin = [];
try {
bool trustSelfSigned = true;
HttpClient httpClient = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) =>
trustSelfSigned);
IOClient http = new IOClient(httpClient);
final response = await http.post(_url,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode({
"aa": a,
"bb": b,
}));
Map<String, dynamic> responseJson = json.decode(response.body);
if (responseJson["status"] == "200") {
datalogin.add(LoginRespon(
status: responseJson['status'],
data: Data(
name: responseJson['data']['name'],
position: responseJson['data']['pos'])));
return datalogin;
} else {
print("ppp");
}
} on Exception {
rethrow;
}
return datalogin;
}
}
and here is for stream builder
isClick
? StreamBuilder(
stream: bloc.login(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return Text("success");
} else if (snapshot.hasError) {
return Text(
snapshot.error.toString());
}
return Text("wait..");
},
)
: FlatButton(
child: Text("Login"),
onPressed: () {
setState(() {
isClick = true;
});
},
),
is there a way so that I can call print(snapshot.data) inside if (snapshot.hasData)
You need to pass argument which required in method otherwise it will not successfully responce (200) and it will throw error.