Compare commits

...

19 Commits

Author SHA1 Message Date
Nathan Anderson 7ffeb2d199 dart analyzer 2023-12-07 16:24:17 -07:00
Nathan Anderson 3e140d6310 0.0.10 2023-12-07 16:23:11 -07:00
Nathan Anderson dcc5cf010f 0.0.10, remove that pesky Y 2023-12-07 16:03:02 -07:00
Nathan Anderson 713f35c692 dart formatting 2023-12-07 15:38:08 -07:00
Nathan Anderson abcbf96d08 0.0.9 2023-12-07 15:37:29 -07:00
Nathan Anderson f4b05dbccf Fix versioning 2023-12-05 17:45:59 -07:00
Nathan Anderson ef189517c1 Changed lower sdk constraint 2023-12-05 11:08:39 -07:00
Nathan Anderson 462e40308f 0.0.6 release 2023-12-01 16:12:42 -07:00
Nathan Anderson d7d27a1cf5 Update pubspec to 0.0.5 2023-11-22 10:55:29 -07:00
Nathan Anderson 1c918f72f9 Update changelog to 0.0.5 2023-11-22 10:54:15 -07:00
Nathan Anderson 4b0e4a98de Added web fix for platform call and static analysis fixes 2023-11-22 10:52:52 -07:00
n8r 645d0749da Merge pull request 'Updateto 0.0.4' (#2) from 0.0.4 into main
Reviewed-on: #2
2023-11-21 13:39:47 -07:00
Nathan Anderson bd91c1f814 Updateto 0.0.4 2023-11-21 13:38:02 -07:00
Nathan Anderson a8e571ca7b Fix focus on mobile when navigating away and coming back to field, added readme pizaz 2023-11-21 11:46:42 -07:00
Nathan Anderson dd52ffb398 0.0.3 released, see CHANGELOG.md 2023-11-21 09:45:25 -07:00
Nathan Anderson d4c697dde8 updated example file and removed build artifacts from git repo 2023-11-17 16:18:27 -07:00
Nathan Anderson a356775a39 Added sad path test, implemented custom styling, added CVC error handling and Stripe request for card token retreival 2023-11-17 16:17:28 -07:00
Nathan Anderson f9fba42a79 Changelog updated 2023-11-14 17:37:03 -07:00
Nathan Anderson 106ba444e1 Update readme and bump version 2023-11-14 17:35:48 -07:00
34 changed files with 2015 additions and 557 deletions
+1
View File
@@ -28,3 +28,4 @@ migrate_working_dir/
.dart_tool/ .dart_tool/
.packages .packages
build/ build/
+62 -1
View File
@@ -1,3 +1,64 @@
## 0.0.10
- One little 'Y' I missed
- Fixed out of range error with `_adjustSelection`
## 0.0.9
- Drastically improved usability and performance with flutter web and canvaskit renderer, especially on mobile
- Using streams to more accurately call `widget.onValidCardDetails` when the card details are valid and completed
- Added `cursorColor` customization
- Reworked widget life cycle so that hot reloads work as expected (resizing, focus, etc.).
## 0.0.8
- Updated dart sdk constraints again... oops (>=3.0.0)
## 0.0.7
- Changed pubspec versioning to allow lower SDK constraints (>=2.12.0)
## 0.0.6
- Improved assertion and error messaging when missing stripe implements
- Added better doc comments
- Fixed `CardTextField.delayToShowLoading`, now it uses it
- Fixed bad assertion logic when providing stripe keys
- Added ability to make Stripe call with `GlobalKey`
- Refactored method `onTokenReceived` to `onStripeResponse` to be clearer
- Refactored method `onCardDetailsComplete` to `onValidCardDetails` to be clearer
## 0.0.5
- Fix Web, invalid call to `Platform.isAndroid`
- Analysis issues fixed for pub points
## 0.0.4
- Fix for focus and soft keyboard on mobile devices
- Added README gif to show `CardTextField` in action
- Added Icon color customization to `CardProviderIcon` widget
- Fleshed out a dark mode styling example
## 0.0.3
Lots of improvements!
- `CardTextField` now has customizable styles. Stripe integration is natively handled now, returning a card token, if stripe keys are provided.
- `README` revamped with emojis, screen recordings, the whole nine yards.
- `LICENSE` changed from BSD-3.0 to MIT license for pub points, I guess it wasn't being recognized correctly...
- Added `http` depency for handling Stripe token api call.
- Added Widget tests because that should be a thing that gets checked.
- Fix for backspacing on mobile not changing focus.
- Fix for text field spacing when in small form factor
- Much improved usability on mobile, added manually scrolling to element
- Added Icon Size param for card Provider Icon
## 0.0.2
Added dartdoc comments for more pub points!
## 0.0.1 ## 0.0.1
* TODO: Describe initial release. I think it works
+4 -8
View File
@@ -1,11 +1,7 @@
Copyright 2023 Nathan Anderson Copyright 2023 - Nathan Anderson
BSD 3-Clause License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+75 -10
View File
@@ -1,17 +1,55 @@
For information about how to write a good package README, see the guide for
[writing package pages](https://dart.dev/guides/libraries/writing-package-pages).
A simple and clean Stripe Element Card clone, rebuilt in native Flutter widgets. A simple and clean Stripe Element Card clone, rebuilt in native Flutter widgets.
# DISCLAIMER
This is not an officially maintained package by Stripe, but using the html stripe This is not an officially maintained package by Stripe, but using the html stripe
elements they provide with flutter is less than ideal. elements they provide in flutter was inconvenient for me, so I made this package.
## Features # Features
- Card number validation Got to use emojis and taglines for attention grabbing and algorithm hacking:
- No more depending on Flutter Webview
## Getting started - ⚡ Blazingly fast ( its as fast as the rest of flutter )
- 🧹 Cleaner & Easier to Use ( fewer dependencies than the official stripe elements )
- 🛡 Safe and Supports all Flutter Targets ( its native flutter with minimal dependencies )
- ☑ Seemless UI/UX ( hard to match stripe quality, but I think I got pretty close )
- 💳 Built-in Stripe Integration ( guess that one is obvious )
- ☯ Chi Energy Boost ( alright I'm fishing... )
## Why StripeNativeCardField?
- Fewer dependencies: no more depending on Flutter Webview
- Customizable: the entire field can inherit native Flutter styling, i.e. `BoxDecoration()`
- Native Implementation: compiles and loads like the rest of your app, unlike embeded html
- Automatic validation: no `inputFormatters` or `RegExp` needed on your side
The card data can either be retrieved with the `onValidCardDetails` callback, or
you can have the element automatically create a Stripe card token when the fields
are filled out, and return the token with the `onTokenReceived` callback.
### Card Provider Detection
![Card Provider Detection](https://git.fosscat.com/n8r/stripe_native_card_field/raw/branch/main/readme_assets/card_provider_detection.gif)
[Supported Card Providers in Docs](https://pub.dev/documentation/stripe_native_card_field/latest/card_details/CardProviderID.html)
### Customizable Styles
![Customizable Style 1](https://git.fosscat.com/n8r/stripe_native_card_field/raw/branch/main/readme_assets/customizable_style.gif)
This dark mode style example provided [here](https://git.fosscat.com/n8r/stripe_native_card_field/raw/branch/main/example/lib/dark_customization.dart)
For documentation on all of the available customizable aspects of the `CardTextField`, go
to the [API docs here](https://pub.dev/documentation/stripe_native_card_field/latest/stripe_native_card_field/CardTextField-class.html).
### Smooth UX
![Smooth UX](https://git.fosscat.com/n8r/stripe_native_card_field/raw/branch/main/readme_assets/smooth_ux.gif)
Mimics the Stripe html elements behavior wherever possible. Auto focusing / transitioning text fields, backspacing focuses to last field,
automatically validating user input, etc.
# Getting started
- Install the package by running `flutter pub add stripe_native_card_field` - Install the package by running `flutter pub add stripe_native_card_field`
@@ -19,20 +57,47 @@ elements they provide with flutter is less than ideal.
Include the package in a file: Include the package in a file:
```dart ```dart
import 'package:stripe_native_card_field/stripe_native_card_field.dart'; import 'package:stripe_native_card_field/stripe_native_card_field.dart';
``` ```
### For Raw Card Data
Provide a callback for the `CardTextField` to return you the data when its complete.
```dart ```dart
CardTextField( CardTextField(
width: 500, width: 500,
onCardDetailsComplete: (details) { onValidCardDetails: (details) {
// Save the card details to use with your call to Stripe, or whoever // Save the card details to use with your call to Stripe, or whoever
setState(() => _cardDetails = details); setState(() => _cardDetails = details);
}, },
); );
``` ```
## Additional information ### For Stripe Token
Simply provide a function for the `onStripeResponse` callback!
```dart
CardTextField(
width: 500,
stripePublishableKey: 'pk_test_abc123', // Your stripe key here
onStripeResponse: (Map<String, dynamic> data) {
// Save the stripe token to send to your backend
setState(() => _tokenData = data);
},
);
```
If you want more fine-grained control of when the stripe call is made, you
can create a `GlobalKey` and access the `CardTextFieldState`, calling the
`getStripeResponse()` function yourself. See the provided [example](https://pub.dev/packages/stripe_native_card_field/example)
for details. If you choose this route, do not provide an `onStripeResponse` callback, or you will end up
making two calls to stripe!
# Additional information
Repository located [here](https://git.fosscat.com/n8r/stripe_native_card_field) Repository located [here](https://git.fosscat.com/n8r/stripe_native_card_field)
Please email me at n8r@fosscat.com for any issues or PRs.
+19
View File
@@ -0,0 +1,19 @@
<component name="libraryTable">
<library name="Dart SDK">
<CLASSES>
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/async" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/collection" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/convert" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/core" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/developer" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/html" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/io" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/isolate" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/math" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/mirrors" />
<root url="file:///home/nate/Tooling/flutter/bin/cache/dart-sdk/lib/typed_data" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component>
+15
View File
@@ -0,0 +1,15 @@
<component name="libraryTable">
<library name="KotlinJavaRuntime">
<CLASSES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-stdlib.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-stdlib-sources.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-reflect-sources.jar!/" />
<root url="jar://$KOTLIN_BUNDLED$/lib/kotlin-test-sources.jar!/" />
</SOURCES>
</library>
</component>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/example.iml" filepath="$PROJECT_DIR$/example.iml" />
<module fileurl="file://$PROJECT_DIR$/android/example_android.iml" filepath="$PROJECT_DIR$/android/example_android.iml" />
</modules>
</component>
</project>
+6
View File
@@ -0,0 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="main.dart" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/lib/main.dart" />
<method />
</configuration>
</component>
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="main.dart" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/lib/main.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="0">
<caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="ToolWindowManager">
<editor active="true" />
<layout>
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
</layout>
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
</navigator>
<panes>
<pane id="ProjectPane">
<option name="show-excluded-files" value="false" />
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="dart.analysis.tool.window.force.activate" value="true" />
<property name="show.migrate.to.gradle.popup" value="false" />
</component>
</project>
@@ -0,0 +1,19 @@
package io.flutter.plugins;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
/**
* Generated file. Do not edit.
* This file is generated by the Flutter tool based on the
* plugins that support the Android platform.
*/
@Keep
public final class GeneratedPluginRegistrant {
private static final String TAG = "GeneratedPluginRegistrant";
public static void registerWith(@NonNull FlutterEngine flutterEngine) {
}
}
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android" name="Android">
<configuration>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="GEN_FOLDER_RELATIVE_PATH_APT" value="/gen" />
<option name="GEN_FOLDER_RELATIVE_PATH_AIDL" value="/gen" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/app/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/app/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/app/src/main/assets" />
<option name="LIBS_FOLDER_RELATIVE_PATH" value="/app/src/main/libs" />
<option name="PROGUARD_LOGS_FOLDER_RELATIVE_PATH" value="/app/src/main/proguard_logs" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/app/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/app/src/main/kotlin" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
</content>
<orderEntry type="jdk" jdkName="Android API 29 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Flutter for Android" level="project" />
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
</component>
</module>
Binary file not shown.
Vendored Executable
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+90
View File
@@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
sdk.dir=/home/nate/Android/Sdk
flutter.sdk=/home/nate/Tooling/flutter
flutter.buildMode=debug
flutter.versionName=1.0.0
flutter.versionCode=1
Binary file not shown.
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/lib" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.idea" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Flutter Plugins" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
</component>
</module>
@@ -0,0 +1,19 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GeneratedPluginRegistrant_h
#define GeneratedPluginRegistrant_h
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface GeneratedPluginRegistrant : NSObject
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry;
@end
NS_ASSUME_NONNULL_END
#endif /* GeneratedPluginRegistrant_h */
@@ -0,0 +1,14 @@
//
// Generated file. Do not edit.
//
// clang-format off
#import "GeneratedPluginRegistrant.h"
@implementation GeneratedPluginRegistrant
+ (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry {
}
@end
+101
View File
@@ -0,0 +1,101 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:stripe_native_card_field/card_details.dart';
import 'package:stripe_native_card_field/stripe_native_card_field.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Native Stripe Field Demo',
theme: ThemeData(
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple, brightness: Brightness.dark),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
CardDetailsValidState? state;
String? errorText;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black45,
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Enter your card details below:',
style: TextStyle(color: Colors.white70),
),
),
CardTextField(
width: 300,
onValidCardDetails: (details) {
if (kDebugMode) {
print(details);
}
},
textStyle:
const TextStyle(fontFamily: 'Lato', color: Colors.tealAccent),
hintTextStyle:
const TextStyle(fontFamily: 'Lato', color: Colors.teal),
errorTextStyle: const TextStyle(color: Colors.purpleAccent),
boxDecoration: BoxDecoration(
color: Colors.black54,
border: Border.all(
color: Colors.teal.withAlpha(255),
),
),
errorBoxDecoration: BoxDecoration(
color: Colors.black54,
border: Border.all(width: 3.0, color: Colors.purple),
),
cardIconColor: 'teal',
cardIconErrorColor: '#b65cc2',
overrideValidState: state,
errorText: errorText,
),
ElevatedButton(
child: const Text('Set manual error'),
onPressed: () => setState(() {
errorText = 'There is a problem';
state = CardDetailsValidState.invalidCard;
}),
)
],
),
),
);
}
}
+46 -36
View File
@@ -1,5 +1,6 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:stripe_native_card_field/card_details.dart';
import 'package:stripe_native_card_field/stripe_native_card_field.dart'; import 'package:stripe_native_card_field/stripe_native_card_field.dart';
void main() { void main() {
@@ -13,23 +14,9 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
title: 'Flutter Demo', debugShowCheckedModeBanner: false,
title: 'Native Stripe Field Demo',
theme: ThemeData( theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a blue toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true, useMaterial3: true,
), ),
@@ -41,15 +28,6 @@ class MyApp extends StatelessWidget {
class MyHomePage extends StatefulWidget { class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title}); const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title; final String title;
@override @override
@@ -57,26 +35,58 @@ class MyHomePage extends StatefulWidget {
} }
class _MyHomePageState extends State<MyHomePage> { class _MyHomePageState extends State<MyHomePage> {
CardDetailsValidState? state;
String? errorText;
// Creating a global key here allows us to call the `getStripeResponse()`
// inside the CardTextFieldState widget in our build method. See below
final _key = GlobalKey<CardTextFieldState>();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cardField = CardTextField(
key: _key,
loadingWidgetLocation: LoadingLocation.above,
stripePublishableKey: 'pk_test_abc123testmykey',
width: 600,
onValidCardDetails: (details) {
if (kDebugMode) {
print(details);
}
},
overrideValidState: state,
errorText: errorText,
);
return Scaffold( return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center( body: Center(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[ children: <Widget>[
const Text( const Padding(
'Enter your card details below:', padding: EdgeInsets.all(8.0),
child: Text(
'Enter your card details below:',
),
), ),
CardTextField( cardField,
width: 500, ElevatedButton(
onCardDetailsComplete: (details) { child: const Text('Set manual error'),
if (kDebugMode) print('Got card details: $details'); onPressed: () => setState(() {
errorText = 'There is a problem';
state = CardDetailsValidState.invalidCard;
}),
),
const SizedBox(height: 12),
ElevatedButton(
child: const Text('Get Stripe token'),
onPressed: () async {
// Here we use the global key to get the stripe data, rather than
// using the `onStripeResponse` callback in the widget
final tok = await _key.currentState?.getStripeResponse();
if (kDebugMode) print(tok);
}, },
), )
], ],
), ),
), ),
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+38 -14
View File
@@ -45,10 +45,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: collection name: collection
sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.17.2" version: "1.18.0"
cupertino_icons: cupertino_icons:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -91,6 +91,22 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
http:
dependency: transitive
description:
name: http
sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b"
url: "https://pub.dev"
source: hosted
version: "4.0.2"
lints: lints:
dependency: transitive dependency: transitive
description: description:
@@ -119,10 +135,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.9.1" version: "1.10.0"
path: path:
dependency: transitive dependency: transitive
description: description:
@@ -164,18 +180,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: stack_trace name: stack_trace
sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.11.0" version: "1.11.1"
stream_channel: stream_channel:
dependency: transitive dependency: transitive
description: description:
name: stream_channel name: stream_channel
sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.1" version: "2.1.2"
string_scanner: string_scanner:
dependency: transitive dependency: transitive
description: description:
@@ -190,7 +206,7 @@ packages:
path: ".." path: ".."
relative: true relative: true
source: path source: path
version: "0.0.1" version: "0.0.9"
term_glyph: term_glyph:
dependency: transitive dependency: transitive
description: description:
@@ -203,10 +219,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.6.0" version: "0.6.1"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c
url: "https://pub.dev"
source: hosted
version: "1.3.2"
vector_graphics: vector_graphics:
dependency: transitive dependency: transitive
description: description:
@@ -243,10 +267,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: web name: web
sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.1.4-beta" version: "0.3.0"
xml: xml:
dependency: transitive dependency: transitive
description: description:
@@ -256,5 +280,5 @@ packages:
source: hosted source: hosted
version: "6.3.0" version: "6.3.0"
sdks: sdks:
dart: ">=3.1.3 <4.0.0" dart: ">=3.2.0-194.0.dev <4.0.0"
flutter: ">=3.7.0-0" flutter: ">=3.7.0-0"
+8 -1
View File
@@ -4,7 +4,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1 version: 1.0.0+1
environment: environment:
sdk: '>=3.1.3 <4.0.0' sdk: '>=3.0.0 <4.0.0'
dependencies: dependencies:
flutter: flutter:
@@ -25,3 +25,10 @@ flutter:
uses-material-design: true uses-material-design: true
fonts:
- family: Lato
fonts:
- asset: assets/Lato-Medium.ttf
weight: 400
+62 -40
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
/// Class encapsulating the card's data /// Class encapsulating the card's data
@@ -7,19 +9,22 @@ import 'package:flutter/foundation.dart';
/// when fields are filled and validated as correct. /// when fields are filled and validated as correct.
class CardDetails { class CardDetails {
CardDetails({ CardDetails({
required dynamic cardNumber, required String? cardNumber,
required String? securityCode, required this.securityCode,
required this.expirationString, required this.expirationString,
required this.postalCode, required this.postalCode,
}) : _cardNumber = cardNumber { }) : _cardNumber = cardNumber {
this.securityCode = int.tryParse(securityCode ?? '');
checkIsValid(); checkIsValid();
} }
/// Sets every field to null, a default /// Sets every field to null, a default
/// `CardDetails` when nothing has been entered. /// `CardDetails` when nothing has been entered.
factory CardDetails.blank() { factory CardDetails.blank() {
return CardDetails(cardNumber: null, securityCode: null, expirationString: null, postalCode: null); return CardDetails(
cardNumber: null,
securityCode: null,
expirationString: null,
postalCode: null);
} }
/// Returns the CardNumber as a `String` with the spaces removed. /// Returns the CardNumber as a `String` with the spaces removed.
@@ -28,27 +33,33 @@ class CardDetails {
set cardNumber(String? num) => _cardNumber = num; set cardNumber(String? num) => _cardNumber = num;
String? _cardNumber; String? _cardNumber;
int? securityCode; String? securityCode;
String? postalCode; String? postalCode;
String? expirationString; String? expirationString;
DateTime? expirationDate; DateTime? expirationDate;
bool _complete = false; bool _complete = false;
ValidState _validState = ValidState.blank; CardDetailsValidState _validState = CardDetailsValidState.blank;
int _lastCheckHash = 0; int _lastCheckHash = 0;
CardProvider? provider; CardProvider? provider;
StreamController<CardDetails> onCompleteController = StreamController();
set overrideValidState(CardDetailsValidState state) => _validState = state;
/// Checks the validity of the `CardDetails` and returns the result. /// Checks the validity of the `CardDetails` and returns the result.
ValidState get validState { CardDetailsValidState get validState {
checkIsValid(); checkIsValid();
return _validState; return _validState;
} }
// TODO rename to be more clear String get expMonth => isComplete ? expirationString!.split('/').first : '';
String get expYear => isComplete ? expirationString!.split('/').last : '';
/// Returns true if `_cardNumber` is null, or /// Returns true if `_cardNumber` is null, or
/// if the _cardNumber matches the detected `provider`'s /// if the _cardNumber matches the detected `provider`'s
/// card lenght, defaulting to 16. /// card lenght, defaulting to 16.
bool get cardNumberFilled => bool get cardNumberFilled => _cardNumber == null
_cardNumber == null ? false : (provider?.cardLength ?? 16) == _cardNumber!.replaceAll(' ', '').length; ? false
: (provider?.cardLength ?? 16) == _cardNumber!.replaceAll(' ', '').length;
/// Returns true if all details are complete and valid /// Returns true if all details are complete and valid
/// otherwise, return false. /// otherwise, return false.
@@ -57,6 +68,14 @@ class CardDetails {
return _complete; return _complete;
} }
/// Detects if the card is complete, then broadcasts
/// card details to `onCompleteController`
void broadcastStatus() {
if (isComplete) {
onCompleteController.add(this);
}
}
/// The maximum length of the INN (identifier) /// The maximum length of the INN (identifier)
/// of a card provider. /// of a card provider.
int get maxINNLength => 4; int get maxINNLength => 4;
@@ -73,10 +92,13 @@ class CardDetails {
return; return;
} }
_complete = false;
_lastCheckHash = currentHash; _lastCheckHash = currentHash;
if (_cardNumber == null && expirationString == null && securityCode == null && postalCode == null) { if (_cardNumber == null &&
_complete = false; expirationString == null &&
_validState = ValidState.blank; securityCode == null &&
postalCode == null) {
_validState = CardDetailsValidState.blank;
return; return;
} }
final nums = _cardNumber! final nums = _cardNumber!
@@ -87,67 +109,63 @@ class CardDetails {
) )
.toList(); .toList();
if (!_luhnAlgorithmCheck(nums)) { if (!_luhnAlgorithmCheck(nums)) {
_complete = false; _validState = CardDetailsValidState.invalidCard;
_validState = ValidState.invalidCard;
return; return;
} }
if (_cardNumber == null || !cardNumberFilled) { if (_cardNumber == null || !cardNumberFilled) {
_complete = false; _validState = CardDetailsValidState.missingCard;
_validState = ValidState.missingCard;
return; return;
} }
if (expirationString == null) { if (expirationString == null) {
_complete = false; _validState = CardDetailsValidState.missingDate;
_validState = ValidState.missingDate;
return; return;
} }
final expSplits = expirationString!.split('/'); final expSplits = expirationString!.split('/');
if (expSplits.length != 2 || expSplits.last == '') { if (expSplits.length != 2 || expSplits.last == '') {
_complete = false; _validState = CardDetailsValidState.missingDate;
_validState = ValidState.missingDate;
return; return;
} }
final month = int.parse(expSplits.first[0] == '0' ? expSplits.first[1] : expSplits.first); final month = int.parse(
expSplits.first[0] == '0' ? expSplits.first[1] : expSplits.first);
if (month < 1 || month > 12) { if (month < 1 || month > 12) {
_complete = false; _validState = CardDetailsValidState.invalidMonth;
_validState = ValidState.invalidMonth;
return; return;
} }
final year = 2000 + int.parse(expSplits.last); final year = 2000 + int.parse(expSplits.last);
final date = DateTime(year, month); final date = DateTime(year, month);
if (date.isBefore(DateTime.now())) { if (date.isBefore(DateTime.now())) {
_complete = false; _validState = CardDetailsValidState.dateTooEarly;
_validState = ValidState.dateTooEarly;
return; return;
} else if (date.isAfter(DateTime.now().add(const Duration(days: 365 * 50)))) { } else if (date
_complete = false; .isAfter(DateTime.now().add(const Duration(days: 365 * 50)))) {
_validState = ValidState.dateTooLate; _validState = CardDetailsValidState.dateTooLate;
return; return;
} }
expirationDate = date; expirationDate = date;
if (securityCode == null) { if (securityCode == null) {
_complete = false; _validState = CardDetailsValidState.missingCVC;
_validState = ValidState.missingCVC; return;
}
if (provider != null && securityCode!.length != provider!.cvcLength) {
_validState = CardDetailsValidState.invalidCVC;
return; return;
} }
if (postalCode == null) { if (postalCode == null) {
_complete = false; _validState = CardDetailsValidState.missingZip;
_validState = ValidState.missingZip;
return; return;
} }
if (!RegExp(r'^\d{5}(-\d{4})?$').hasMatch(postalCode!)) { if (!RegExp(r'^\d{5}(-\d{4})?$').hasMatch(postalCode!)) {
_complete = false; _validState = CardDetailsValidState.invalidZip;
_validState = ValidState.invalidZip;
return; return;
} }
_complete = true; _complete = true;
_validState = ValidState.ok; _validState = CardDetailsValidState.ok;
} catch (err, st) { } catch (err, st) {
if (kDebugMode) { if (kDebugMode) {
print('Error while validating CardDetails: $err\n$st'); print('Error while validating CardDetails: $err\n$st');
} }
_complete = false; _complete = false;
_validState = ValidState.error; _validState = CardDetailsValidState.error;
} }
} }
@@ -236,7 +254,7 @@ class CardDetails {
} }
/// Enum of validation states a `CardDetails` object can have. /// Enum of validation states a `CardDetails` object can have.
enum ValidState { enum CardDetailsValidState {
ok, ok,
error, error,
blank, blank,
@@ -252,7 +270,7 @@ enum ValidState {
invalidZip, invalidZip,
} }
/// Enum of supported U.S. Card Providers /// Enum of supported Card Providers
enum CardProviderID { enum CardProviderID {
americanExpress, americanExpress,
dinersClub, dinersClub,
@@ -273,7 +291,11 @@ class CardProvider {
int cvcLength; int cvcLength;
CardProvider( CardProvider(
{required this.id, required this.cardLength, required this.cvcLength, this.innValidNums, this.innValidRanges}) { {required this.id,
required this.cardLength,
required this.cvcLength,
this.innValidNums,
this.innValidRanges}) {
// Must provide one or the other // Must provide one or the other
assert(innValidNums != null || innValidRanges != null); assert(innValidNums != null || innValidRanges != null);
// Do not provide empty list of valid nums // Do not provide empty list of valid nums
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
/// Error class that `CardTextField` throws if any errors are encountered
class CardTextFieldError extends Error {
/// Details provided for the error
String? details;
CardTextFieldErrorType type;
CardTextFieldError(this.type, {this.details});
@override
String toString() {
return 'CardTextFieldError-${type.name}: $details';
}
}
/// Enum to add typing to the `CardTextFieldErrorType`
enum CardTextFieldErrorType {
stripeImplementation,
unknown,
}
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,16 +1,16 @@
name: stripe_native_card_field name: stripe_native_card_field
description: A native flutter implementation of the elegant Stripe Card Field. description: A native flutter implementation of the elegant Stripe Card Field.
version: 0.0.1 version: 0.0.10
repository: https://git.fosscat.com/n8r/stripe_native_card_field repository: https://git.fosscat.com/n8r/stripe_native_card_field
environment: environment:
sdk: '>=3.1.3 <4.0.0' sdk: '>=3.0.0 <4.0.0'
flutter: ">=1.17.0"
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
flutter_svg: ^2.0.9 flutter_svg: ^2.0.9
http: ^1.1.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 924 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 MiB

-111
View File
@@ -1,111 +0,0 @@
---
author: Nathan Anderson
date: MMMM dd, YYYY
paging: Slide %d / %d
---
# Steps to Publish
1. Initialize Library
2. Write Library
4. Write some tests
5. Publish!
---
# 1. Initialize Your Library!
---
## Publishing Requirements
- You must include a LICENSE file.
- Your package must be smaller than 100 MB after gzip compression.
- Your package should depend only on hosted dependencies (from the default pub
package server) and SDK dependencies (sdk: flutter).
- You must have a Google Account,
---
## Publishing is Forever
To make sure projects don't break after using a dependency, you are unable to
take down a published project.
If you will have regrets publishing, turn back now.
---
## Initialize Project
Creating a flutter library is straightforward, simply run the command
```sh
flutter create -template=package <package_name>
```
Creates a new flutter project with a simple example library inside.
---
## Select License
This is important. The dart team recommends the BSD-3 clause license.
---
## pubspec.yaml Considerations
In the `pubspec.yaml` file, it is recommended to include a "homepage" or "repository"
field. This gets popultated into the package page on [pub.dev](https://pub.dev).
```yaml
# Top of pubspec.yaml file
name: stripe_native_card_field
description: A native flutter implementation of Stripes Card Field.
version: 0.0.1
repository: https://git.fosscat.com/nathananderson98/stripe_native_card_field
```
---
# 2. Write Your Library
---
## Important Bits
Be sure to include a `README.md` file at the root of your library as this is
what determines the content of your packages page on [pub.dev](https://pub.dev)
A `CHANGELOG.md` file can also be included and will fill out a tab on the
package's page
### Verified Publisher
You can publish under a verified domain as a "Verified Publisher". Its a bit of
a process. But it adds a cool checkmark on your package and you can hide your email.
---
## Tests
Its a good idea to include some Unit Tests and Widget Tests for your library.
---
# 3. Publishing!
---
## Dry Run
To see the results of what publishing will look like without going through with it run
```sh
dart pub publish --dry-run
```
## Helpful Links
[Dart Publishing Guide](https://dart.dev/tools/pub/publishing)
+129 -19
View File
@@ -18,22 +18,23 @@ void main() {
CardDetails? details; CardDetails? details;
final cardField = CardTextField( final cardField = CardTextField(
width: width, width: width,
onCardDetailsComplete: (cd) => details = cd, onValidCardDetails: (cd) => details = cd,
); );
await tester.pumpWidget(cardFieldWidget(cardField)); await tester.pumpWidget(baseCardFieldWidget(cardField));
final input = TestTextInput(); final input = TestTextInput();
final cardState = tester.state(find.byType(CardTextField)) as CardTextFieldState; final cardState =
tester.state(find.byType(CardTextField)) as CardTextFieldState;
assertEmptyTextFields(tester, width); assertEmptyTextFields(tester, cardState.isWideFormat);
await tester.tap(find.byType(CardTextField)); await tester.tap(find.byType(CardTextField));
expect(cardState.cardNumberFocusNode.hasFocus, true); expect(cardState.cardNumberFocusNode.hasFocus, true);
// await enterTextByKey(tester, key: cardFieldKey, text: '4242424242424242'); // await enterTextByKey(tester, key: cardFieldKey, text: '4242424242424242');
input.enterText("4242424242424242"); input.enterText("4242424242424242");
await tester.pumpAndSettle(); await tester.pump();
expect(cardState.cardNumberFocusNode.hasFocus, false); expect(cardState.cardNumberFocusNode.hasFocus, false);
expect(cardState.expirationFocusNode.hasFocus, true); expect(cardState.expirationFocusNode.hasFocus, true);
@@ -44,20 +45,23 @@ void main() {
// Backspace should move focus back to card number // Backspace should move focus back to card number
await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace); await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace);
await tester.pumpAndSettle(); await tester.pump();
expect(getTextFormField(expirationFieldKey).controller?.text, ''); expect(getTextFormField(expirationFieldKey).controller?.text, '');
expect(getTextFormField(cardFieldKey).controller?.text, '4242 4242 4242 424'); expect(getTextFormField(cardFieldKey).controller?.text,
'4242 4242 4242 424');
expect(cardState.cardNumberFocusNode.hasFocus, true); expect(cardState.cardNumberFocusNode.hasFocus, true);
expect(cardState.expirationFocusNode.hasFocus, false); expect(cardState.expirationFocusNode.hasFocus, false);
// Postal code should now be gone // Postal code should now be gone
expect(find.text("Postal Code"), findsNothing); // FIXME this doesnt work
// expect(find.text("Postal Code"), findsNothing);
// When using TestTextInput, any enterText() clears what is currently in focused field // When using TestTextInput, any enterText() clears what is currently in focused field
input.enterText("4242424242424242"); input.enterText("4242424242424242");
await tester.pumpAndSettle(); await tester.pump();
expect(getTextFormField(cardFieldKey).controller?.text, '4242 4242 4242 4242'); expect(getTextFormField(cardFieldKey).controller?.text,
'4242 4242 4242 4242');
expect(cardState.cardNumberFocusNode.hasFocus, false); expect(cardState.cardNumberFocusNode.hasFocus, false);
expect(cardState.expirationFocusNode.hasFocus, true); expect(cardState.expirationFocusNode.hasFocus, true);
// Postal code should move back into view // Postal code should move back into view
@@ -70,7 +74,7 @@ void main() {
expect(cardState.expirationFocusNode.hasFocus, false); expect(cardState.expirationFocusNode.hasFocus, false);
expect(cardState.securityCodeFocusNode.hasFocus, true); expect(cardState.securityCodeFocusNode.hasFocus, true);
// FIXME this isn't transitioning focus correctly in test // FIXME this isn't transitioning focus correctly in test
input.enterText("333"); input.enterText("333");
await tester.sendKeyDownEvent(LogicalKeyboardKey.tab); await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
await tester.pump(); await tester.pump();
@@ -88,13 +92,116 @@ void main() {
await input.receiveAction(TextInputAction.done); await input.receiveAction(TextInputAction.done);
await tester.pump(); await tester.pump();
final expectedCardDetails = CardDetails(cardNumber: '4242 4242 4242 4242', securityCode: '333', expirationString: '10/28', postalCode: '91555'); final expectedCardDetails = CardDetails(
cardNumber: '4242 4242 4242 4242',
securityCode: '333',
expirationString: '10/28',
postalCode: '91555');
// print('${expectedCardDetails.toString()}\n${details?.toString()}');
expect(details?.hash, expectedCardDetails.hash); expect(details?.hash, expectedCardDetails.hash);
}, },
); );
testWidgets(
'CardTextField: GIVEN the user enters invalid input WHEN each text field is filled THEN the correct error messages are displayed',
(tester) async {
const width = 500.0;
CardDetails? details;
final cardField = CardTextField(
width: width,
onValidCardDetails: (cd) => details = cd,
);
await tester.pumpWidget(baseCardFieldWidget(cardField));
final input = TestTextInput();
final cardState =
tester.state(find.byType(CardTextField)) as CardTextFieldState;
assertEmptyTextFields(tester, cardState.isWideFormat);
await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
expect(cardState.cardNumberFocusNode.hasFocus, true);
input.enterText('4242424242424222');
await tester.pump();
expect(find.text('Your card number is invalid.'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace);
await tester.pump();
expect(cardState.cardNumberFocusNode.hasFocus, true);
input.enterText('4242424242424242');
await tester.pump();
expect(cardState.expirationFocusNode.hasFocus, true);
input.enterText('0055');
await tester.pump();
expect(
find.text("Your card's expiration month is invalid."), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace);
await tester.pump();
expect(cardState.expirationFocusNode.hasFocus, true);
input.enterText('1099');
await tester.pump();
expect(
find.text("Your card's expiration year is invalid."), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace);
await tester.pump();
expect(cardState.expirationFocusNode.hasFocus, true);
input.enterText('0228');
await tester.pump();
expect(cardState.securityCodeFocusNode.hasFocus, true);
// FIXME this isnt transitioning focus correctly in test
input.enterText('123');
await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(cardState.postalCodeFocusNode.hasFocus, true);
input.enterText('1234');
// Pressing enter doesnt work here...
await input.receiveAction(TextInputAction.done);
await tester.pump();
expect(find.text("The postal code you entered is not correct."),
findsOneWidget);
await tester.tap(find.byType(CardTextField));
// Tab from security field to get zipcode focus
await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
expect(cardState.postalCodeFocusNode.hasFocus, true);
input.enterText('12345');
await input.receiveAction(TextInputAction.done);
await tester.pump();
final expectedCardDetails = CardDetails(
cardNumber: '4242 4242 4242 4242',
expirationString: '02/28',
securityCode: '123',
postalCode: '12345');
expect(details?.hash, expectedCardDetails.hash);
});
} }
Widget cardFieldWidget(CardTextField cardField) => MaterialApp( Widget baseCardFieldWidget(CardTextField cardField) => MaterialApp(
home: Scaffold( home: Scaffold(
body: Center( body: Center(
child: Column( child: Column(
@@ -106,14 +213,17 @@ Widget cardFieldWidget(CardTextField cardField) => MaterialApp(
), ),
); );
void assertEmptyTextFields(WidgetTester tester, double width) { void assertEmptyTextFields(WidgetTester tester, bool isWideFormat) {
expect(find.text("Card number"), findsOneWidget); if (isWideFormat) {
expect(find.text("MM/YY"), findsOneWidget); expect(find.text("Card number"), findsOneWidget);
expect(find.text("CVC"), findsOneWidget); expect(find.text("MM/YY"), findsOneWidget);
expect(find.text("Postal Code"), findsNothing); expect(find.text("CVC"), findsOneWidget);
}
// expect(find.text("Postal Code"), findsNothing);
} }
Future<void> enterTextByKey(WidgetTester tester, {required String key, required String text}) async { Future<void> enterTextByKey(WidgetTester tester,
{required String key, required String text}) async {
await tester.enterText(find.byKey(ValueKey(key)), text); await tester.enterText(find.byKey(ValueKey(key)), text);
} }