savers_app_sdk 1.0.8
savers_app_sdk: ^1.0.8 copied to clipboard
Flutter SDK for the Savers hosted app: WebView bridge, native maps/dialer/browser, device/session helpers, and encrypted URL generation.
example/lib/main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:savers_app_sdk/savers_app_sdk.dart';
import 'screens/api_hub_screen.dart';
void main() {
runApp(const SaversDemoApp());
}
class SaversDemoApp extends StatelessWidget {
const SaversDemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Savers App Flutter SDK Sample',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2563EB)),
scaffoldBackgroundColor: const Color(0xFFF8FAFC),
),
home: const InitializeSdkScreen(),
);
}
}
/// Step 1: collect SDK credentials and call SaversAppSDK.initialize().
class InitializeSdkScreen extends StatefulWidget {
const InitializeSdkScreen({super.key});
@override
State<InitializeSdkScreen> createState() => _InitializeSdkScreenState();
}
class _InitializeSdkScreenState extends State<InitializeSdkScreen> {
final _formKey = GlobalKey<FormState>();
final _apiKeyController = TextEditingController();
final _encryptionKeyController = TextEditingController();
final _pRefCodeController = TextEditingController();
final _environment = SaversSdkHostedEnvironment.sandbox;
bool _isSubmitting = false;
@override
void dispose() {
_apiKeyController.dispose();
_encryptionKeyController.dispose();
_pRefCodeController.dispose();
super.dispose();
}
Future<void> _initializeSdk() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _isSubmitting = true);
try {
LogsManager.log(LogType.general, 'Initializing SDK...');
await SaversAppSDK.initialize(
apiKey: _apiKeyController.text.trim(),
encryptionKey: _encryptionKeyController.text.trim(),
pRefCode: _pRefCodeController.text.trim(),
environment: _environment,
);
if (!mounted) return;
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const InitializeUserSessionScreen()),
);
} catch (e) {
LogsManager.log(LogType.general, 'SDK init failed: $e');
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('SDK init failed: $e')));
} finally {
if (mounted) setState(() => _isSubmitting = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const _Header(step: '1', subtitle: 'Initialize SDK'),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _InfoBanner(
text:
'All the values below can be collected from savers.com.',
linkLabel: 'saversapp.com',
linkUrl: 'https://saversapp.com',
),
Form(
key: _formKey,
child: _Card(
title: 'SDK Credentials',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_LabeledField(
label: 'API Key',
controller: _apiKeyController,
hint: 'API_KEY',
),
_LabeledField(
label: 'Encryption Key',
controller: _encryptionKeyController,
hint: 'BASE64_ENCRYPTION_KEY',
),
_LabeledField(
label: 'Program Ref Code',
controller: _pRefCodeController,
hint: 'PROGRAM_REFERRAL_CODE',
),
const SizedBox(height: 12),
const Text(
'Environment',
style: TextStyle(
fontSize: 12,
color: Color(0xFF6B7280),
),
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 12,
),
decoration: BoxDecoration(
color: const Color(0xFFF3F4F6),
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: const Color(0xFFBDBDBD),
),
),
child: Text(
_environment.name,
style: const TextStyle(
fontSize: 16,
color: Color(0xFF111827),
),
),
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: _PrimaryButton(
label: 'Initialize SDK',
color: const Color(0xFF2563EB),
onPressed: _isSubmitting
? null
: _initializeSdk,
),
),
],
),
),
),
],
),
),
),
],
),
),
);
}
}
/// Step 2: collect user profile fields and call SaversAppSDK.initializeUserSession().
class InitializeUserSessionScreen extends StatefulWidget {
const InitializeUserSessionScreen({super.key});
@override
State<InitializeUserSessionScreen> createState() =>
_InitializeUserSessionScreenState();
}
class _InitializeUserSessionScreenState
extends State<InitializeUserSessionScreen> {
final _formKey = GlobalKey<FormState>();
final _userIdController = TextEditingController();
final _firstnameController = TextEditingController();
final _lastnameController = TextEditingController();
final _emailController = TextEditingController();
final _phoneController = TextEditingController();
final _dobController = TextEditingController();
final _cityController = TextEditingController();
final _zipcodeController = TextEditingController();
String _pv = '0';
String _ev = '1';
bool _isSubmitting = false;
@override
void dispose() {
_userIdController.dispose();
_firstnameController.dispose();
_lastnameController.dispose();
_emailController.dispose();
_phoneController.dispose();
_dobController.dispose();
_cityController.dispose();
_zipcodeController.dispose();
super.dispose();
}
Future<void> _initializeUserSession() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _isSubmitting = true);
try {
await SaversAppSDK.initializeUserSession(
userId: _userIdController.text.trim(),
firstname: _firstnameController.text.trim(),
lastname: _lastnameController.text.trim(),
email: _emailController.text.trim(),
phone: _phoneController.text.trim(),
dob: _dobController.text.trim(),
city: _cityController.text.trim(),
zipcode: _zipcodeController.text.trim(),
pv: _pv,
ev: _ev,
);
try {
final deviceId = await getDeviceId();
await SaversAppSDK.registerDevice(deviceId: deviceId);
} catch (e) {
LogsManager.log(LogType.general, 'Device registration failed: $e');
}
if (!mounted) return;
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const LaunchOptionsScreen()));
} catch (e) {
LogsManager.log(LogType.general, 'User session init failed: $e');
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('User session init failed: $e')));
} finally {
if (mounted) setState(() => _isSubmitting = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const _Header(step: '2', subtitle: 'Initialize User Session'),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _InfoBanner(
text:
'Use any one of the valid user profiles from your source '
'system for testing.',
),
Form(
key: _formKey,
child: _Card(
title: 'User Profile',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_LabeledField(
label: 'User Id',
controller: _userIdController,
hint: 'USER_ID',
),
_LabeledField(
label: 'First Name',
controller: _firstnameController,
hint: 'FIRST_NAME',
),
_LabeledField(
label: 'Last Name',
controller: _lastnameController,
hint: 'LAST_NAME',
),
_LabeledField(
label: 'Email',
controller: _emailController,
hint: 'EMAIL',
),
_LabeledField(
label: 'Phone',
controller: _phoneController,
hint: 'PHONE',
),
_LabeledField(
label: 'DOB',
controller: _dobController,
required: false,
hint: 'DOB',
),
_LabeledField(
label: 'City',
controller: _cityController,
required: false,
hint: 'CITY',
),
_LabeledField(
label: 'Zipcode',
controller: _zipcodeController,
required: false,
hint: 'ZIPCODE',
),
Row(
children: [
Expanded(
child: _ZeroOneDropdown(
label: 'PV',
value: _pv,
onChanged: (v) => setState(() => _pv = v),
),
),
const SizedBox(width: 12),
Expanded(
child: _ZeroOneDropdown(
label: 'EV',
value: _ev,
onChanged: (v) => setState(() => _ev = v),
),
),
],
),
const SizedBox(height: 20),
Row(
children: [
SizedBox(
width: 88,
child: _PrimaryButton(
label: 'Back',
color: const Color(0xFF6B7280),
onPressed: _isSubmitting
? null
: () => Navigator.of(context).pop(),
),
),
const SizedBox(width: 12),
Expanded(
child: _PrimaryButton(
label: 'Initialize User Session',
color: const Color(0xFF2563EB),
onPressed: _isSubmitting
? null
: _initializeUserSession,
),
),
],
),
],
),
),
),
],
),
),
),
],
),
),
);
}
}
/// Step 3: launch the hosted app or the API test hub.
class LaunchOptionsScreen extends StatefulWidget {
const LaunchOptionsScreen({super.key});
@override
State<LaunchOptionsScreen> createState() => _LaunchOptionsScreenState();
}
class _LaunchOptionsScreenState extends State<LaunchOptionsScreen> {
bool _isLoadingUrl = false;
Future<void> _openHostedApp() async {
setState(() => _isLoadingUrl = true);
try {
final url = await SaversAppSDK.generateUrl(Screen(name: 'Explore'));
if (!mounted) return;
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => HostedAppScreen(saversAppUrl: url)),
);
} catch (e) {
LogsManager.log(LogType.general, 'generateUrl failed: $e');
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('generateUrl failed: $e')));
} finally {
if (mounted) setState(() => _isLoadingUrl = false);
}
}
void _openApiTests() {
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const ApiHubScreen()));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
const _Header(step: '3', subtitle: 'Launch'),
Expanded(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_Card(
title: 'Hosted App',
child: SizedBox(
width: double.infinity,
child: _PrimaryButton(
label: _isLoadingUrl
? 'Generating URL...'
: 'Open Hosted App',
color: const Color(0xFF14B8A6),
onPressed: _isLoadingUrl ? null : _openHostedApp,
),
),
),
_Card(
title: 'API Testing',
child: SizedBox(
width: double.infinity,
child: _PrimaryButton(
label: 'Open API Tests',
color: const Color(0xFF10B981),
onPressed: _openApiTests,
),
),
),
],
),
),
),
],
),
),
);
}
}
class HostedAppScreen extends StatelessWidget {
const HostedAppScreen({super.key, required this.saversAppUrl});
final String saversAppUrl;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: HostedAppComponent(
saversAppUrl: saversAppUrl,
onSaversSdkMessage: (raw, postBack) {
try {
final msg = jsonDecode(raw);
if (msg is Map && msg['action'] == 'USER_SESSION_ID') {
final payload = msg['payload'];
LogsManager.log(
LogType.general,
'[Demo] USER_SESSION_ID from WebView',
['payloadKeys=${payload is Map ? payload.keys.toList() : payload}'],
);
}
} catch (_) {}
handleWebMessage(raw, postBack: postBack);
},
),
);
}
}
class _Header extends StatelessWidget {
final String step;
final String subtitle;
const _Header({required this.step, required this.subtitle});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
color: const Color(0xFF2563EB),
child: Row(
children: [
const Expanded(
child: Text(
'Savers App Flutter SDK Sample',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: Colors.white,
),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 12),
Flexible(
child: Text(
'Step $step · $subtitle',
style: const TextStyle(fontSize: 12, color: Color(0xFFE5E7EB)),
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
}
class _Card extends StatelessWidget {
final String title;
final Widget child;
const _Card({required this.title, required this.child});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: const [
BoxShadow(
color: Color(0x1A000000),
blurRadius: 8,
offset: Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(fontSize: 12, color: Color(0xFF6B7280)),
),
const SizedBox(height: 8),
child,
],
),
);
}
}
class _InfoBanner extends StatelessWidget {
final String text;
final String? linkLabel;
final String? linkUrl;
const _InfoBanner({required this.text, this.linkLabel, this.linkUrl});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFEFF6FF),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: const Color(0xFFBFDBFE)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
text,
style: const TextStyle(fontSize: 13, color: Color(0xFF1E3A8A)),
),
if (linkLabel != null && linkUrl != null) ...[
const SizedBox(height: 4),
InkWell(
onTap: () => openBrowser(linkUrl!),
child: Text(
'Open $linkLabel',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: Color(0xFF1E3A8A),
decoration: TextDecoration.underline,
),
),
),
],
],
),
);
}
}
class _LabeledField extends StatelessWidget {
final String label;
final TextEditingController controller;
final bool required;
final String? hint;
const _LabeledField({
required this.label,
required this.controller,
this.required = true,
this.hint,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextFormField(
controller: controller,
decoration: InputDecoration(
labelText: required ? label : '$label (optional)',
hintText: hint,
border: const OutlineInputBorder(),
isDense: true,
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
),
validator: required
? (value) =>
(value == null || value.trim().isEmpty) ? 'Required' : null
: null,
),
);
}
}
class _ZeroOneDropdown extends StatelessWidget {
final String label;
final String value;
final ValueChanged<String> onChanged;
const _ZeroOneDropdown({
required this.label,
required this.value,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: const TextStyle(fontSize: 12, color: Color(0xFF6B7280)),
),
const SizedBox(height: 4),
DropdownButtonFormField<String>(
initialValue: value,
decoration: const InputDecoration(
border: OutlineInputBorder(),
isDense: true,
contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
),
items: const [
DropdownMenuItem(value: '0', child: Text('0')),
DropdownMenuItem(value: '1', child: Text('1')),
],
onChanged: (v) {
if (v != null) onChanged(v);
},
),
],
);
}
}
class _PrimaryButton extends StatelessWidget {
final String label;
final Color color;
final VoidCallback? onPressed;
const _PrimaryButton({
required this.label,
required this.color,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 40,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: color,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
onPressed: onPressed,
child: Text(
label,
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
),
);
}
}