I am trying to learn how to (and best practices) to integrate Stripe into my mobile app.
I know from another post (Why there is no billing address in stripe Checkout) that Stripe has deprecated Billing Address Support however, I'd still want to be able to add that functionality into my app.
Currently the code I have is:
Future<void> createPaymentMethod(BuildContext context,
Map<String, String> billingAddress, String name, String phoneNumber) async {
StripePayment.setStripeAccount(null);
// Here to add the credit Card
PaymentMethod paymentMethod = PaymentMethod();
paymentMethod = await StripePayment.paymentRequestWithCardForm(
CardFormPaymentRequest(),
).then((PaymentMethod paymentMethod) {
paymentMethod.billingDetails = BillingDetails.fromJson({
'address': billingAddress,
'name': name,
'phone': phoneNumber,
});
return paymentMethod;
}).catchError((e) {
print('Error Card: ${e.toString()}');
});
paymentMethod != null
? processPaymentAsDirectCharge(paymentMethod,
context)
: AwesomeDialog(
context: context,
title: 'Uh oh! A wild error has appeared!',
desc:
'Seems like we cant process this card. Please double check your input or try a different card',
animType: AnimType.SCALE,
dialogType: DialogType.WARNING,
btnOkOnPress: () {})
.show();
}
Where I have a button that does:
onPressed: () {
createPaymentMethod(
context,
{
'city': cityController.text,
'line1': streetAddressController.text,
'postal_code': zipcodeController.text, // **postal_code does not show up for some reason**
'state': stateController.text
},
fullNameController.text,
'8007897890');
}
And What I got back from the paymentMethod in my console is:
paymentMethod: {
created: 1599242290.0,
id: pm_someIdHereThatGotReplacedByThis,
livemode: false,
type: card,
billingDetails: {name: John Doe,
phone: phoneNumber,
address: {city: Doggo Town, line1: 555 Puppy Street, state: CA}},
card: {addressLine1: null, addressLine2: null, brand: visa, country: US, expMonth: 4,
expYear: 2024, funding: credit, last4: 4242}}
However, in my Logs in Stripe it shows:
{
"id": "pm_someIdHereThatGotReplacedByThis",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": null,
"name": null,
"phone": null
},
"card": {
"brand": "visa",
"checks": {
"address_line1_check": null,
"address_postal_code_check": null,
"cvc_check": null
},
"country": "US",
"exp_month": 4,
"exp_year": 2024,
"funding": "credit",
"generated_from": null,
"last4": "4242",
"networks": {
"available": [
"visa"
],
"preferred": null
},
"three_d_secure_usage": {
"supported": true
},
"wallet": null
},
"created": 1599240880,
"customer": null,
"livemode": false,
"metadata": {
},
"type": "card"
}
my question is:
How do I setup my function so that the "checks" and "billing_details" fields will be filled with the information provided by the customer? Should I be adding something to the function
paymentMethod = await StripePayment.paymentRequestWithCardForm(
CardFormPaymentRequest()).then(...)
This is the field I am talking about:
"checks": {
"address_line1_check": null,
"address_postal_code_check": null,
"cvc_check": null
},
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": null,
"name": null,
"phone": null
},
Thanks
Related
Here I'm registering users by category from the app but can't register. But when I register a user from postman it can. What is the issue, kindly help me on this. Thanks.
Here is the scenario.
Here are id's for categories
{
"total": 6,
"per_page": 15,
"current_page": 1,
"last_page": 1,
"next_page_url": "",
"prev_page_url": "",
"from": 0,
"to": 6,
"success": true,
"en_message": "",
"ar_message": "",
"data": [
{
"id": 3,
"ar_name": "ستوديو",
"en_name": "Studio",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-06.webp",
"parent": 0,
"parent_details": null
},
{
"id": 4,
"ar_name": "تطبيقات الموبايل والويب",
"en_name": "Web & App",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-07.webp",
"parent": 0,
"parent_details": null
},
{
"id": 2,
"ar_name": "طباعة الصحيفه",
"en_name": "Printing Press",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-05.webp",
"parent": 0,
"parent_details": null
},
{
"id": 5,
"ar_name": "الفعاليات",
"en_name": "Events",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-08.webp",
"parent": 0,
"parent_details": null
},
{
"id": 1,
"ar_name": "التواصل الاجتماعي",
"en_name": "Social Media",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-04.webp",
"parent": 0,
"parent_details": null
},
{
"id": 6,
"ar_name": "التصميم الداخلي",
"en_name": "Interior Design",
"photo": "http://newprotectco.com/hello/SD08/msf/Untitled-2-09.webp",
"parent": 0,
"parent_details": null
}
],
"status": 200
}
When I register a user by category from postman It can be.
I'm only adding field for category where I'm facing issues and the rest are working.
Category filed form postman
From the application when I try to register it doesn't show. Why?
Map<String, String> bdy = {
"name": companyName,
"username": email,
"password": password,
"phone": phone,
"trade_license": tradeLicence,
"category_id": categories,
};
Where categories are in drop down like this.
List<String> category = [
'Social Media',
'Printing Press',
'Studio',
'Web & App',
'Events',
'Interior Design',
];
String? selectedCategory;
void _agencyRegistration() {
else if ((selectedCategory ?? "").isEmpty) {
Utils.flushBarErrorMessage(LanguageStringKeys.instance.TypeYourField.tr, context);
}
Provider.of<AgencyRegistrationService>(context, listen: false).doSignUp(
context,
companyName,
email,
password,
phone,
(selectedCategory?? ""),
image,
);
DropdownButtonFormField(
isExpanded: true,
decoration: textFormFieldsDecoration(
LanguageStringKeys.instance.Category.tr,
AppColors.fIconsAndTextColor,
AppColors.fIconsAndTextColor,
),
items: category
.map((item) => DropdownMenuItem(
value: item,
child: Center(child: SmallText(text: item, color: Colors.black)),
))
.toList(),
value: selectedCategory,
onChanged: (item) => setState(() => selectedCategory = item as String?)),
}
I have trying to figure out in some question but there is no case like me. I am getting the code from tutorial and I have understand it. However, the problem is in the tutorial. It uses static JSON (list) where mine using dynamic which contain keys.
Here is my code
class CompileAd {
String status;
String notification;
Map<int,DataAd> adData;
CompileAd({
required this.status,
required this.notification,
required this.adData,
});
factory CompileAd.fromJson(Map<String, dynamic> json) => CompileAd(
status: json["status"],
notification: json["notification"],
adData: Map<int,DataAd>.from(
json["adData"].map((x) => DataAd.fromJson(x))), => ERROR HERE
);
Map<String, dynamic> toJson() => {
"status": status,
"notification": notification,
"adData": Map<dynamic,dynamic>.from(adData.map((key,x) => x.toJson())), => HERE ALSO (Actually, I wish to use "jsonEncode(adData)" since its working but no idea which one better)
};
}
Error Log
lib/class/adClass.dart:27:69: Error: A value of type 'Map<String,
dynamic>' can't be returned from a function with return type
'MapEntry<dynamic, dynamic>'.
'Map' is from 'dart:core'.
'MapEntry' is from 'dart:core'.
"adData": Map<dynamic,dynamic>.from(adData.map((key,x) => x.toJson())),
^
Here is the json object
adData => (keyID,adObject)
{
"adData": {
"77289": {
"id": 77289,
"username": "magdatjahja#gmail.com",
"category": "rumah",
"subCategory": "rumah",
"type": "dijual",
"uniqueId": "6436",
"title": "Jual Rumah di Mazenta Bintaro Tangerang Selatan",
"slug": "jual-rumah-di-mazenta-bintaro-tangerang-selatan",
"content": "Jual rumah di mazento bintaro tangerang selatan\r\n\r\nSatu-satunya hunian premium di kawasan Bintaro bernuansa Japan Ambiance Living :\r\n\r\nType unit :\r\n\ud83d\udc49 Type 6 \r\nLuas Tanah: 72m2 \r\nLuas Bangunan: 83m2 \r\nKamar Tidur: 3 \r\nKamar Mandi: 2 \r\n\r\n\ud83c\udf81Dapatkan Promo Early Bird Price !!!\ud83c\udf81\r\n\u2705HARGA MULAI RP.1,8 M\r\n\u27053 unit AC 1 Pk\r\n\u2705Free Mini Canopy\r\n\u2705 Lucky Bowl up to Iphone13\r\n\u2705 SmartDoorlock\r\n\r\nLokasi\r\n\ud83d\ude97 Hanya 3 menit ke BXchange Mall Bintaro!\r\n\ud83d\ude97 Hanya 2-3 menit ke pintu tol! dan jumlah unit SANGAT terbatas!\r\n\ud83d\ude97Hanya 3 Menit Statiun Jurang Mangu\r\n\ud83d\ude97Hanya 3 menit UPJ University\r\n\r\n\r\nHubungi AGENT MERKETING\r\nMagda 08118897878",
"bid": 2000,
"balance": 1,
"price": "1800000000",
"province": "banten",
"regency": "tangerang selatan",
"district": "",
"village": "",
"complex": "",
"rd": 1,
"premier": "2022-03-22 11:33:13",
"partner": 1,
"privateSync": "0000-00-00 00:00:00",
"penaltyTime": null,
"data": {
"price": {
"price": "1800000000"
},
"priceUnit": "",
"province": "banten",
"regency": "tangerang selatan",
"district": "",
"village": "",
"additional": {
"address": "Bintaro, Tangerang Selatan",
"complex": "",
"lt": "72",
"lb": "83",
"bedroom": "3",
"bathroom": "2",
"maidbedroom": "",
"maidbathroom": "",
"floor": "",
"garage": "",
"carports": "",
"electricity": "",
"orientation": "",
"interior": ""
},
"facebook": "2022-03-22 14:54:05",
"twitter": "0000-00-00 00:00:00",
"pinterest": "0000-00-00 00:00:00",
"tumblr": "0000-00-00 00:00:00",
"premier": "2022-03-22 11:33:13",
"partner": true,
"penaltyTime": "2022-03-22 11:32:01",
"instagram": "2022-03-22 14:47:14"
},
"images": {
"images": ["jual-rumah-di-mazenta-bintaro-tangerang-selatan-0XOV3B.jpg", "jual-rumah-di-mazenta-bintaro-tangerang-selatan-VS38QN.jpg", "jual-rumah-di-mazenta-bintaro-tangerang-selatan-14RHI3.jpg"],
"imagesAdditional": [],
"images360": []
},
"video": {
"1": "https:\/\/youtu.be\/CA6iNWEDa1E"
},
"sosmed": 0,
"view": 28,
"contact": 0,
"status": "active",
"checked": 1,
"sold": "0000-00-00 00:00:00",
"modify": "0000-00-00 00:00:00",
"waktu": "2022-03-21 17:40:03",
"dir": "\/uploads\/images\/2022\/03\/77289\/",
"url": "\/properti\/tangerang-selatan\/6436-jual-rumah-di-mazenta-bintaro-tangerang-selatan\/"
}
},
"status": "success",
"notification": "Berhasil memproses permintaan"
}
I really appreciate any answers. Thank you.
I have integrated flutter_stripe 2.0.1 plugins in my flutter application using Firebase CLI. getting a successful response of paymentIntent from firebase provided URL. But in the Stripe dashboard payment status is Incomplete.
Below is my node.js code
index.js file
const functions = require('firebase-functions');
const stripe = require('stripe')(functions.config().stripe.testkey);
exports.stripePayment = functions.https.onRequest(async (req, res) => {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1,
currency: 'usd'
},
function(err, paymentIntent) {
if(err != null){
console.log(err);
} else {
res.json({
paymentIntent: paymentIntent.client_secret,
})
}
}
)
});
Below is my flutter code
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Stripe.publishableKey = stripePublishableKey;
Stripe.merchantIdentifier = 'merchant.flutter.stripe.test'; //any string works
await Stripe.instance.applySettings();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DashboradPage(),
);
}
}
class DashboradPage extends StatefulWidget {
const DashboradPage({Key? key}) : super(key: key);
#override
_DashboradPageState createState() => _DashboradPageState();
}
class _DashboradPageState extends State<DashboradPage> {
Map<String, dynamic>? paymentIntentData;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stripe Examples'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
makePayment();
},
child: Text('Pay Amount'),
),
),
);
}
Future<void> makePayment() async {
final url = Uri.parse(
'https://us-central1-stripeflutterdemo.cloudfunctions.net/stripePayment');
final header = {'Content-Type': 'application/json'};
try {
final response = await http.get(url, headers: header);
paymentIntentData = json.decode(response.body);
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentData?['paymentIntent'] ?? '',
applePay: true,
googlePay: true,
style: ThemeMode.light,
merchantCountryCode: 'US',
merchantDisplayName: 'Flutter Stripe Store Demo',
));
setState(() {});
displayPaymentSheet();
} catch (e) {
print(e);
displaySnackbar(e.toString());
}
}
Future<void> displayPaymentSheet() async {
try {
await Stripe.instance.presentPaymentSheet();
// await Stripe.instance.presentPaymentSheet(
// parameters: PresentPaymentSheetParameters(
// clientSecret: paymentIntentData?['paymentIntent'] ?? '',
// confirmPayment: true,
// ),
// );
setState(() {
paymentIntentData = null;
});
displaySnackbar('Payment succesfully completed');
} catch (e) {
print(e);
displaySnackbar(e.toString());
}
}
void displaySnackbar(String msg) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(msg),
),
);
}
}
Below is the postman response of URL mentioned in makePayment()
I have used payment sheet, when I clicked on the Pay button it is redirecting to webview (Authentication completed) but in the Stripe dashboard payment status is Incomplete.
Stripe Dashboard Payment Event data
PaymentIntent status:requires_payment_method,
PaymentIntent status:requires_action
From Stripe
payment_intent.payment_failed
View event detail
Event data
{
"id": "pi_3JpZh7SIKwX0CSUQ0sUoM9wK",
"object": "payment_intent",
"last_payment_error": {
"message": "As per Indian regulations, export transactions require a description. More info here: https://stripe.com/docs/india-exports",
"param": "description",
"payment_method": {
"id": "pm_1JpZijSIKwX0CSUQ7u91wths",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": "45612",
"state": null
},
"email": null,
"name": null,
"phone": null
},
"card": {
"brand": "visa",
"checks": {
"address_line1_check": null,
"address_postal_code_check": "unchecked",
"cvc_check": "unchecked"
},
"country": "US",
"exp_month": 4,
"exp_year": 2044,
"fingerprint": "EK9VAoccqqCLBqQk",
"funding": "credit",
"generated_from": null,
"last4": "4242",
"networks": {
"available": [
"visa"
],
"preferred": null
},
"three_d_secure_usage": {
"supported": true
},
"wallet": null
},
"created": 1635431806,
"customer": null,
"livemode": false,
"metadata": {
},
"type": "card"
},
"type": "invalid_request_error"
},
"livemode": false,
"next_action": null,
"status": "requires_payment_method",
"amount": 1,
"amount_capturable": 0,
"amount_received": 0,
"application": null,
"application_fee_amount": null,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"charges": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges?payment_intent=pi_3JpZh7SIKwX0CSUQ0sUoM9wK"
},
"client_secret": "pi_3JpZh7SIKwX0CSUQ0sUoM9wK_secret_oVhK5CmrcHjImvFMyoo51GCXy",
"confirmation_method": "automatic",
"created": 1635431705,
"currency": "usd",
"customer": null,
"description": null,
"invoice": null,
"metadata": {
},
"on_behalf_of": null,
"payment_method": null,
"payment_method_options": {
"card": {
"installments": null,
"network": null,
"request_three_d_secure": "automatic"
}
},
"payment_method_types": [
"card"
],
"receipt_email": null,
"review": null,
"setup_future_usage": "off_session",
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"transfer_data": null,
"transfer_group": null
}
Below is the iPhone screenshot
According to the Stripe documentation, the required_payment_method message as a status means you have not attached a payment method to your payment intent:
When the PaymentIntent is created, it has a status of requires_payment_method until a payment method is attached.
There is an official document explaining how to integrate Stripe payments with your Firebase backend. It provides all the required code and steps to properly set up payments with Stripe. In the sample code inside the index.js file, they include additional objects when creating the payment intent with stripe.paymentIntents.create()
const payment = await stripe.paymentIntents.create(
{
amount,
currency,
customer,
Payment_method, //payment method when creating the payment intent
off_session: false,
confirm: true,
confirmation_method: 'manual',
},
{ idempotencyKey }
);
Since your sample is missing the payment method, it could explain the error you are receiving, as the PaymentIntent is being created without a payment method. I recommend following the guide to cover all the required steps to avoid further errors that might be present. You can also see the full sample code, which is documented and can be customized for your use case and the flutter_stripe library.
I want to get raw json data from GraphQL flutter.
here is part of the data I want to get:
{
"data": {
"countries": [
{
"name": "Andorra",
"code": "AD",
"native": "Andorra",
"phone": "376"
},
{
"name": "United Arab Emirates",
"code": "AE",
"native": "دولة الإمارات العربية المتحدة",
"phone": "971"
},
but this is the result that GraphQL returns to me:
{__typename: Query,
countries: [{__typename: Country, name: Andorra, code: AD, native: Andorra, phone: 376},
{__typename: Country, name: United Arab Emirates,
code: AE, native: دولة الإمارات العربية المتحدة, phone: 971},
the format is all wrong...
and this is my code:
void getCountryName() async {
pageState(AppState.loading);
String q = """
{
countries {
name
code
native
phone
}
}
""";
QueryResult res = await countriesClient.query(
QueryOptions(
document: gql(q),
optimisticResult: Country,
fetchPolicy: FetchPolicy.networkOnly,
),
);
}
print(res.data);
Currently I am getting this kind of issue from my code. I was trying to solved this problem continuously. But could not fund the solution of this problem.
Json Codes
{
"id": 22,
"client_need_id": 46,
"clientNeed": {
"id": 46,
"client_id": 29,
"perpose": "Pooja",
"details": "Test",
"when": "2020-08-28 20:11",
"for": null,
"accepted_by": 10,
"name": "Sfgdsa",
"mobile": "567896789",
"email": "sdnsd#asd.com",
"org_name": "Buii",
"address": "Tata",
"city": "Kolkata",
"state": "West Bengal",
"pincode": "789009",
"country": "India",
"latitude": null,
"longitude": null,
"client_ip": null,
"device": null,
"created_at": "2020-08-23T14:40:06.000000Z",
"updated_at": "2020-09-02T18:07:40.000000Z"
},
"quote_details": null,
"quote_amount": null,
"isCalled": 0,
"isChecked": 0,
"isAccept": 1,
"isGoing": 0,
"checkIn": "2020-09-03 02:00:00",
"checkOut": "2020-09-03 02:00:15",
"pandit_id": 10,
"pandit": {
"id": 10,
"name": "Ajay Roy",
"mobile": "8013138886",
"sms_token": null,
"mobile_verified_at": null,
"email": "ajay#abc.com",
"email_token": null,
"email_verified_at": null,
"password": "5f4dcc3b5aa765d61d8327deb882cf99",
"remember_token": null,
"avatar": null,
"address": "dum dum cantonment",
"city": "Kolkata",
"state": "West Bengal",
"country": "India",
"pincode": 700028,
"location_id": null,
"travelled": null,
"adharcard": "34567890",
"pancard": "ATD8994568",
"specialisation": "Vastushastri",
"services": [
"Artrology",
"Numerology"
],
"min_charge": "500",
"max_charge": "1000",
"online_charge": "700",
"qualification": "Test1",
"experience": "12 Years",
"language": "Bengali",
"active": "0",
"varify": "1",
"payment_mode": "{\"bank_name\":\"HDFC Bank\",\"bank_address\":\"Dum Dum Cant\",\"ifsc_code\":\"HDFC098765\",\"account_no\":\"987654654678\",\"account_holder\":\"Abit Roy\"}",
"created_at": "2020-08-31T19:03:56.000000Z",
"updated_at": "2020-09-16T12:40:54.000000Z"
},
"visits": [
{
"id": 70,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": "2020-09-03 02:00:00",
"checkOut": null,
"created_at": "2020-09-02T20:30:00.000000Z",
"updated_at": "2020-09-02T20:30:00.000000Z"
},
{
"id": 71,
"pandit_activity_id": 22,
"pandit_id": 10,
"checkIn": null,
"checkOut": "2020-09-03 02:00:15",
"created_at": "2020-09-02T20:30:15.000000Z",
"updated_at": "2020-09-02T20:30:15.000000Z"
}
]
}
Lead Model
import 'dart:convert';
import 'package:PandeetApp/models/client_need.dart';
import 'package:PandeetApp/models/pandit.dart';
import 'package:PandeetApp/models/visit.dart';
import 'package:PandeetApp/services/lead.dart';
class Lead extends LeadService {
int id;
int clientNeedId;
ClientNeed clientNeed;
String quoteDetails;
String quoteAmount;
int isCalled;
int isChecked;
int isAccept;
int isGoing;
String checkIn;
String checkOut;
int panditId;
Pandit pandit;
List<Visit> visits;
Lead({
this.id,
this.clientNeedId,
this.clientNeed,
this.quoteDetails,
this.quoteAmount,
this.isCalled,
this.isChecked,
this.isAccept,
this.isGoing,
this.checkIn,
this.checkOut,
this.panditId,
this.pandit,
this.visits,
});
Future<List<Lead>> fetchLeads() async {
var datas = await super.fetchDatas();
var dataList = json.decode(datas);
var leads = dataList.map((e) => Lead.fromJson(e)).toList();
return leads;
}
factory Lead.fromJson(Map<String, dynamic> json) {
List<Visit> visits = List<Visit>();
if (json['visits'] != null) {
json['visits'].forEach((v) {
visits.add(Visit.fromJson(v));
});
}
return Lead(
id: json['id'],
clientNeedId: json['client_need_id'],
clientNeed: json['clientNeed'] != null
? ClientNeed.fromJson(json['clientNeed'])
: ClientNeed(),
quoteDetails: json['quote_details'],
quoteAmount: json['quote_amount'],
isCalled: json['isCalled'],
isChecked: json['isChecked'],
isAccept: json['isAccept'],
isGoing: json['isGoing'],
checkIn: json['checkIn'],
checkOut: json['checkOut'],
panditId: json['pandit_id'],
pandit:
json['pandit'] != null ? Pandit.fromJson(json['pandit']) : Pandit(),
visits: visits,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
if (this.clientNeed != null) {
data['clientNeed'] = this.clientNeed.toJson();
}
data['quote_details'] = this.quoteDetails;
data['quote_amount'] = this.quoteAmount;
data['isCalled'] = this.isCalled;
data['isChecked'] = this.isChecked;
data['isAccept'] = this.isAccept;
data['isGoing'] = this.isGoing;
data['checkIn'] = this.checkIn;
data['checkOut'] = this.checkOut;
if (this.pandit != null) {
data['pandit'] = this.pandit.toJson();
}
if (this.visits != null) {
data['visits'] = this.visits.map((v) => v.toJson()).toList();
}
return data;
}
}
Screen Part
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List leads = snapshot.data;
// print(leads.length); // Data Not Getting Here
if (leads.length > 0) {
return dataList(leads);
} else {
return Container(
padding: EdgeInsets.only(top: 200),
child: Text("You have no clients"),
);
}
} else if (snapshot.hasError) {
print(snapshot.error);
return Text("Server is Down now. Try again later");
}
return Container(
padding: EdgeInsets.only(top: 200),
child: CircularProgressIndicator(
backgroundColor: Colors.redAccent,
),
);
},
);
I think here have the problem. I was completed my project but this type of problem ruin my project. I could not understand where i am wrong for this problem. Exact line number could not found. Give just hint but where exactly problem not understandable. Please help me as soon as possible.
Don't cast the snapshot data as List instead use var. Try the print results before error and proceed further
FutureBuilder<List<Lead>>(
future: lead.fetchLeads(),
builder: (context, snapshot) {
if (snapshot.hasData) {
var leads = snapshot.data; // use var instead of List
// try this in your case it is received as String
print(leads.runtimeType.toString())
// if it is string convert to List.
var leadsJson = jsonDecode(leads)