Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null safety migration #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ class MyApp extends StatefulWidget {
}

class _MyAppState extends State<MyApp> {

final TextEditingController controller = new CreditCardMaskedTextController();

@override
Expand Down Expand Up @@ -76,7 +75,8 @@ class _MyAppState extends State<MyApp> {

void _getCustomer() async {
try {
final customer = await CustomerSession.instance.retrieveCurrentCustomer();
final customer =
await CustomerSession.instance!.retrieveCurrentCustomer();
print(customer);
} catch (error) {
print(error);
Expand All @@ -91,9 +91,9 @@ class _MyAppState extends State<MyApp> {
StripeCard card = new StripeCard(
number: '4242 4242 4242 4242', cvc: '713', expMonth: 5, expYear: 2019);
card.name = 'Jhonny Bravo';
Stripe.instance.createCardToken(card).then((c) {
Stripe.instance!.createCardToken(card).then((c) {
print(c);
return CustomerSession.instance.addCustomerSource(c.id);
return CustomerSession.instance!.addCustomerSource(c.id);
}).then((source) {
print(source);
}).catchError((error) {
Expand All @@ -103,10 +103,11 @@ class _MyAppState extends State<MyApp> {

void _changeDefaultCard() async {
try {
final customer = await CustomerSession.instance.retrieveCurrentCustomer();
final customer =
await CustomerSession.instance!.retrieveCurrentCustomer();
final card = customer.sources[1].asCard();
final v =
await CustomerSession.instance.updateCustomerDefaultSource(card.id);
await CustomerSession.instance!.updateCustomerDefaultSource(card!.id);
print(v);
} catch (error) {
print(error);
Expand All @@ -115,17 +116,18 @@ class _MyAppState extends State<MyApp> {

void _deleteCard() async {
try {
final customer = await CustomerSession.instance.retrieveCurrentCustomer();
String id;
final customer =
await CustomerSession.instance!.retrieveCurrentCustomer();
late String id;
for (var c in customer.sources) {
StripeCard card = c.asCard();
StripeCard? card = c.asCard();
if (card != null) {
id = card.id;
break;
}
}

final v = await CustomerSession.instance.deleteCustomerSource(id);
final v = await CustomerSession.instance!.deleteCustomerSource(id);
print(v);
} catch (error) {
print(error);
Expand Down Expand Up @@ -153,7 +155,7 @@ class _MyAppState extends State<MyApp> {
}

Map<String, String> _getHeaders(
{String accessToken,
{required String accessToken,
String acceptType = ContentTypeJson,
String contentType = ContentTypeJson}) {
final Map<String, String> headers = new Map<String, String>();
Expand All @@ -173,7 +175,7 @@ class _MyAppState extends State<MyApp> {
class CardItem extends StatelessWidget {
final StripeCard card;

const CardItem({Key key, this.card}) : super(key: key);
const CardItem({Key? key, required this.card}) : super(key: key);

@override
Widget build(BuildContext context) {
Expand Down
54 changes: 24 additions & 30 deletions lib/card_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,23 @@ const int MAX_LENGTH_COMMON = 19;
// because Diners Club has one more space, but one less digit.
const int MAX_LENGTH_AMEX_DINERS = 17;

/**
* Checks the input string to see whether or not it is a valid card number, possibly
* with groupings separated by spaces or hyphens.
*
* @param cardNumber a String that may or may not represent a valid card number
* @return {@code true} if and only if the input value is a valid card number
*/
/// Checks the input string to see whether or not it is a valid card number, possibly
/// with groupings separated by spaces or hyphens.
///
/// @param cardNumber a String that may or may not represent a valid card number
/// @return {@code true} if and only if the input value is a valid card number
bool isValidCardNumber(String cardNumber) {
String normalizedNumber = removeSpacesAndHyphens(cardNumber);
return isValidLuhnNumber(normalizedNumber) &&
isValidCardLength(normalizedNumber);
String? normalizedNumber = removeSpacesAndHyphens(cardNumber);
return isValidLuhnNumber(normalizedNumber ?? '') &&
isValidCardLength(normalizedNumber ?? '', cardBrand: '');
}

/**
* Checks the input string to see whether or not it is a valid Luhn number.
*
* @param cardNumber a String that may or may not represent a valid Luhn number
* @return {@code true} if and only if the input value is a valid Luhn number
*/
/// Checks the input string to see whether or not it is a valid Luhn number.
///
/// @param cardNumber a String that may or may not represent a valid Luhn number
/// @return {@code true} if and only if the input value is a valid Luhn number
bool isValidLuhnNumber(String cardNumber) {
if (cardNumber == null) {
if (cardNumber.isEmpty) {
return false;
}

Expand All @@ -45,7 +41,7 @@ bool isValidLuhnNumber(String cardNumber) {
return false;
}

int digitInteger = getNumericValue(c);
int digitInteger = getNumericValue(c) ?? 0;
isOdd = !isOdd;

if (isOdd) {
Expand All @@ -62,19 +58,17 @@ bool isValidLuhnNumber(String cardNumber) {
return sum % 10 == 0;
}

/**
* Checks to see whether the input number is of the correct length, given the assumed brand of
* the card. This function does not perform a Luhn check.
*
* @param cardNumber the card number with no spaces or dashes
* @param cardBrand a {@link CardBrand} used to get the correct size
* @return {@code true} if the card number is the correct length for the assumed brand
*/
bool isValidCardLength(String cardNumber, {String cardBrand}) {
if (cardBrand == null) {
/// Checks to see whether the input number is of the correct length, given the assumed brand of
/// the card. This function does not perform a Luhn check.
///
/// @param cardNumber the card number with no spaces or dashes
/// @param cardBrand a {@link CardBrand} used to get the correct size
/// @return {@code true} if the card number is the correct length for the assumed brand
bool isValidCardLength(String cardNumber, {required String cardBrand}) {
if (cardBrand.isEmpty) {
cardBrand = getPossibleCardType(cardNumber, shouldNormalize: false);
}
if (cardNumber == null || StripeCard.UNKNOWN == cardBrand) {
if (cardNumber.isEmpty || StripeCard.UNKNOWN == cardBrand) {
return false;
}

Expand All @@ -96,7 +90,7 @@ String getPossibleCardType(String cardNumber, {bool shouldNormalize = true}) {

String spacelessCardNumber = cardNumber;
if (shouldNormalize) {
spacelessCardNumber = removeSpacesAndHyphens(cardNumber);
spacelessCardNumber = removeSpacesAndHyphens(cardNumber) ?? '';
}

if (hasAnyPrefix(spacelessCardNumber, StripeCard.PREFIXES_AMERICAN_EXPRESS)) {
Expand Down
36 changes: 18 additions & 18 deletions lib/credit_card_mask_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ import 'package:flutter/material.dart';
import 'package:stripe_api/stripe_api.dart';

class CreditCardMaskedTextController extends TextEditingController {
CreditCardMaskedTextController({String text}) : super(text: text) {
this._translator = CreditCardMaskedTextController._getDefaultTranslator();
CreditCardMaskedTextController({String text = ''}) : super(text: text) {
_translator = CreditCardMaskedTextController._getDefaultTranslator();

this.addListener(() {
this._updateText(this.text);
addListener(() {
_updateText(this.text);
});

this._updateText(this.text);
_updateText(this.text);
}

static const CARD_MASKS = const {
static const Map<String, String> CARD_MASKS = {
StripeCard.UNKNOWN: '0000 0000 0000 0000',
StripeCard.AMERICAN_EXPRESS: '0000 000000 00000',
StripeCard.DISCOVER: '0000 0000 0000 0000',
Expand All @@ -23,32 +23,32 @@ class CreditCardMaskedTextController extends TextEditingController {
StripeCard.UNIONPAY: '0000 0000 0000 0000',
};

Map<String, RegExp> _translator;
late Map<String, RegExp> _translator;
String _lastUpdatedText = '';

void _updateText(String text) {
if (text != null) {
final cardType = getPossibleCardType(text, shouldNormalize: true);
final mask = CARD_MASKS[cardType];
this.text = this._applyMask(mask, text);
if (text.isNotEmpty) {
final String cardType = getPossibleCardType(text, shouldNormalize: true);
final String mask = CARD_MASKS[cardType]!;
this.text = _applyMask(mask, text);
} else {
this.text = '';
}
this._lastUpdatedText = this.text;
_lastUpdatedText = this.text;
}

void _moveCursorToEnd() {
var text = this._lastUpdatedText;
this.selection = TextSelection.fromPosition(
TextPosition(offset: (text ?? '').length),
var text = _lastUpdatedText;
selection = TextSelection.fromPosition(
TextPosition(offset: text.length),
);
}

@override
set text(String newText) {
if (super.text != newText) {
super.text = newText;
this._moveCursorToEnd();
_moveCursorToEnd();
}
}

Expand Down Expand Up @@ -90,8 +90,8 @@ class CreditCardMaskedTextController extends TextEditingController {
}

// apply translator if match
if (this._translator.containsKey(maskChar)) {
if (this._translator[maskChar].hasMatch(valueChar)) {
if (_translator.containsKey(maskChar)) {
if (_translator[maskChar]!.hasMatch(valueChar)) {
result += valueChar;
maskCharIndex += 1;
}
Expand Down
54 changes: 27 additions & 27 deletions lib/ephemeral_key_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import 'stripe_error.dart';
///
///
///
typedef Future<String> EphemeralKeyProvider(String apiVersion);
typedef EphemeralKeyProvider = Future<String> Function(String apiVersion);

///
///
Expand All @@ -26,28 +26,28 @@ class EphemeralKey extends StripeJsonModel {

static const String NULL = "null";

String _id;
int _created;
int _expires;
bool _liveMode;
String _customerId;
String _object;
String _secret;
String _type;
DateTime _createdAt;
DateTime _expiresAt;
late String _id;
late int _created;
late int _expires;
late bool _liveMode;
late String _customerId;
late String _object;
late String _secret;
late String _type;
late DateTime _createdAt;
late DateTime _expiresAt;

EphemeralKey.fromJson(Map<String, dynamic> json) {
_id = optString(json, FIELD_ID);
_created = optInteger(json, FIELD_CREATED);
_expires = optInteger(json, FIELD_EXPIRES);
_liveMode = optBoolean(json, FIELD_LIVEMODE);
_id = optString(json, FIELD_ID) ?? '';
_created = optInteger(json, FIELD_CREATED) ?? -1;
_expires = optInteger(json, FIELD_EXPIRES) ?? -1;
_liveMode = optBoolean(json, FIELD_LIVEMODE) ?? false;
_customerId = json[FIELD_ASSOCIATED_OBJECTS][0][FIELD_ID];
_type = json[FIELD_ASSOCIATED_OBJECTS][0][FIELD_TYPE];
_object = optString(json, FIELD_OBJECT);
_secret = optString(json, FIELD_SECRET);
_createdAt = new DateTime.fromMillisecondsSinceEpoch(_created);
_expiresAt = new DateTime.fromMillisecondsSinceEpoch(_expires);
_object = optString(json, FIELD_OBJECT) ?? '';
_secret = optString(json, FIELD_SECRET) ?? '';
_createdAt = DateTime.fromMillisecondsSinceEpoch(_created);
_expiresAt = DateTime.fromMillisecondsSinceEpoch(_expires);
}

String get id => _id;
Expand Down Expand Up @@ -90,7 +90,7 @@ class EphemeralKey extends StripeJsonModel {
///
///
class EphemeralKeyManager {
EphemeralKey _ephemeralKey;
EphemeralKey? _ephemeralKey;
final EphemeralKeyProvider ephemeralKeyProvider;
final int timeBufferInSeconds;

Expand All @@ -99,28 +99,28 @@ class EphemeralKeyManager {
///
///
///
Future<EphemeralKey> retrieveEphemeralKey() async {
Future<EphemeralKey?> retrieveEphemeralKey() async {
if (_shouldRefreshKey()) {
String key;
try {
key = await ephemeralKeyProvider(API_VERSION);
} catch (error) {
final e = new StripeAPIError(null, {
final e = StripeAPIError('', {
StripeAPIError.FIELD_MESSAGE:
"Failed to retrive ephemeralKey from server",
});
throw new StripeAPIException(e);
throw StripeAPIException(e);
}

try {
Map<String, dynamic> decodedKey = json.decode(key);
_ephemeralKey = new EphemeralKey.fromJson(decodedKey);
_ephemeralKey = EphemeralKey.fromJson(decodedKey);
} catch (error) {
final e = new StripeAPIError(null, {
final e = StripeAPIError('', {
StripeAPIError.FIELD_MESSAGE:
"Failed to parse Ephemeral Key, Please return the response as it is as you recieved from stripe server",
});
throw new StripeAPIException(e);
throw StripeAPIException(e);
}

return _ephemeralKey;
Expand All @@ -138,7 +138,7 @@ class EphemeralKeyManager {
}

DateTime now = DateTime.now();
final diff = _ephemeralKey.expiresAt.difference(now).abs();
final diff = _ephemeralKey!.expiresAt.difference(now).abs();
return diff.inSeconds < timeBufferInSeconds;
}
}
14 changes: 7 additions & 7 deletions lib/model/address.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ class Address extends StripeJsonModel {
static const String FIELD_POSTAL_CODE = "postal_code";
static const String FIELD_STATE = "state";

String city;
String country;
String line1;
String line2;
String postalCode;
String state;
String? city;
String? country;
String? line1;
String? line2;
String? postalCode;
String? state;

Address({
this.city,
Expand All @@ -37,7 +37,7 @@ class Address extends StripeJsonModel {

@override
Map<String, dynamic> toMap() {
Map<String, Object> hashMap = new Map();
Map<String, dynamic> hashMap = {};
hashMap[FIELD_CITY] = city;
hashMap[FIELD_COUNTRY] = country;
hashMap[FIELD_LINE_1] = line1;
Expand Down
Loading