tnk_ppi_hyb 1.0.0
tnk_ppi_hyb: ^1.0.0 copied to clipboard
TNK hybrid offerwall SDK for Flutter (Android, iOS) with full-screen and embedded offerwall, placement ad lists, reward events and point queries.
example/lib/main.dart
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:tnk_ppi_hyb/tnk_ppi_hyb.dart';
import 'placement_page.dart';
// App IDs are passed at run time so that no real value is committed:
// flutter run --dart-define=TNK_APP_ID=<id>
// Platform specific keys (TNK_ANDROID_APP_ID, TNK_IOS_APP_ID) win when given.
const String _commonAppId = String.fromEnvironment(
'TNK_APP_ID',
defaultValue: 'YOUR_APP_ID',
);
const String _androidAppId = String.fromEnvironment(
'TNK_ANDROID_APP_ID',
defaultValue: _commonAppId,
);
const String _iosAppId = String.fromEnvironment(
'TNK_IOS_APP_ID',
defaultValue: _commonAppId,
);
// Opens the offerwall right after start (handy for screenshots).
const bool _autoOpen = bool.fromEnvironment('TNK_AUTO_OPEN');
// Records privacy consent before the auto open, as an app that collects
// consent itself would (skips the SDK consent dialog).
const bool _autoAgree = bool.fromEnvironment('TNK_AUTO_AGREE');
// Opens the placement screen right after start (handy for screenshots).
const bool _autoPlacement = bool.fromEnvironment('TNK_AUTO_PLACEMENT');
// Starts on the embedded offerwall tab (handy for screenshots on a device):
// --dart-define=TNK_INITIAL_TAB=offerwall
const String _initialTab = String.fromEnvironment('TNK_INITIAL_TAB');
// Shows the offerwall with its own header (title and close X): the offerwall
// tab then does not send `hideHeader`. Handy to check the close request:
// --dart-define=TNK_OFFERWALL_HEADER=true
const bool _offerwallHeader = bool.fromEnvironment('TNK_OFFERWALL_HEADER');
void main() {
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TNK PPI Hyb Example',
theme: ThemeData(colorSchemeSeed: Colors.indigo, useMaterial3: true),
// Follows the system light/dark setting (the offerwall draws itself dark
// in dark mode, so a light SafeArea above it would show as a white band).
darkTheme: ThemeData(
colorSchemeSeed: Colors.indigo,
brightness: Brightness.dark,
useMaterial3: true,
),
themeMode: ThemeMode.system,
home: const ExampleShell(),
);
}
}
/// Bottom navigation with two tabs: the home screen with all the plugin calls,
/// and the offerwall embedded in a screen (`TnkOfferwallView`).
///
/// The offerwall widget is created the first time its tab is selected, and
/// stays in the `IndexedStack` after that, so switching tabs does not load it
/// again. It waits until `TnkPpiHybSdk.initialize` has finished, because the
/// native view loads the offerwall as soon as it can (Android: when first
/// drawn).
class ExampleShell extends StatefulWidget {
const ExampleShell({super.key});
@override
State<ExampleShell> createState() => _ExampleShellState();
}
class _ExampleShellState extends State<ExampleShell> {
static const int _homeTab = 0;
static const int _offerwallTab = 1;
final GlobalKey<_HomePageState> _home = GlobalKey<_HomePageState>();
final TnkOfferwallController _controller = TnkOfferwallController();
int _index = _initialTab == 'offerwall' ? _offerwallTab : _homeTab;
bool _offerwallCreated = false;
bool _sdkReady = false;
bool _offerwallLogged = false;
@override
void initState() {
super.initState();
_offerwallCreated = _index == _offerwallTab;
}
void _log(String line) {
_home.currentState?._add(line);
}
void _select(int index) {
if (index == _index) return;
setState(() {
_index = index;
if (index == _offerwallTab) _offerwallCreated = true;
});
}
void _onSdkReady() {
if (!mounted) return;
setState(() => _sdkReady = true);
}
void _onOfferwallClose() {
// The app decides what "close" means. Here: log it and stay on the tab
// (the native side does not close anything).
// To show the offerwall again after the member changed (setUserName) or
// after the "close" of a network error dialog (the web view is emptied
// first), build TnkOfferwallView again with a new Key.
_log('offerwall onCloseRequested');
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text('Offerwall asked to close')));
}
Widget _offerwall() {
if (!_offerwallCreated || !_sdkReady) return const SizedBox.shrink();
// The top of the screen is the status bar: keep the offerwall below it.
// The bottom is the navigation bar of this Scaffold.
return SafeArea(
bottom: false,
child: TnkOfferwallView(
controller: _controller,
extraParams: _offerwallHeader
? null
: const <String, String>{'hideHeader': '1'},
// IndexedStack keeps the hidden tab enabled: hand the back button to
// the offerwall only while its tab is the selected one.
handleBackButton: _index == _offerwallTab,
onCloseRequested: _onOfferwallClose,
),
);
}
@override
Widget build(BuildContext context) {
if (_offerwallCreated && _sdkReady && !_offerwallLogged) {
_offerwallLogged = true;
WidgetsBinding.instance.addPostFrameCallback(
(_) => _log('offerwall tab created'),
);
}
return Scaffold(
body: IndexedStack(
index: _index,
children: <Widget>[
HomePage(key: _home, onSdkReady: _onSdkReady),
_offerwall(),
],
),
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: _select,
destinations: const <NavigationDestination>[
NavigationDestination(icon: Icon(Icons.home_outlined), label: 'Home'),
NavigationDestination(
icon: Icon(Icons.card_giftcard_outlined),
label: 'Offerwall',
),
],
),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key, this.onSdkReady});
/// Called once the SDK is initialized (also when that failed: the failure is in the log).
final VoidCallback? onSdkReady;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final List<String> _log = <String>[];
final TextEditingController _userName = TextEditingController(
text: 'test-user',
);
final TextEditingController _appId = TextEditingController(text: '12345');
final TextEditingController _scheme = TextEditingController(
text: 'tnkscheme://select_menu?cat_id=1',
);
final List<StreamSubscription<Object?>> _subs =
<StreamSubscription<Object?>>[];
bool _dark = false;
/// Height of the log panel as a share of the body. Default 4/15 (2/5 of the old layout, 2/3 of that).
static const double _logDefaultShare = 4 / 15;
static const double _logMinHeight = 48;
static const double _logMaxShare = 0.8;
static const double _handleHeight = 20;
double? _logHeight;
@override
void initState() {
super.initState();
_subs.add(TnkPpiHybSdk.rewards.listen((r) => _add('rewards: $r')));
_subs.add(TnkPpiHybSdk.events.listen((e) => _add('events: $e')));
_subs.add(
TnkPpiHybSdk.offerwallClosed.listen((_) => _add('offerwallClosed')),
);
unawaited(_start());
}
Future<void> _start() async {
await _run('initialize', () async {
await TnkPpiHybSdk.initialize(
androidAppId: _androidAppId,
iosAppId: _iosAppId,
);
await TnkPpiHybSdk.enableLogging(kDebugMode);
return 'sdk ${await TnkPpiHybSdk.sdkVersion}';
});
if (_autoAgree) {
await _run(
'setAgreePrivacy (auto)',
() => TnkPpiHybSdk.setAgreePrivacy(true),
);
}
widget.onSdkReady?.call();
if (_autoPlacement) {
await Future<void>.delayed(const Duration(seconds: 1));
if (mounted) await _openPlacement();
}
if (_autoOpen) {
await Future<void>.delayed(const Duration(seconds: 1));
await _run('openOfferwall (auto)', () => _open());
}
}
@override
void dispose() {
for (final s in _subs) {
s.cancel();
}
_userName.dispose();
_appId.dispose();
_scheme.dispose();
super.dispose();
}
void _add(String line) {
// Device log only in debug builds: lines can contain app and user data.
if (kDebugMode) {
// ignore: avoid_print
print('[TnkExample] $line');
}
if (!mounted) return;
setState(() => _log.insert(0, '${TimeOfDay.now().format(context)} $line'));
}
Future<void> _run(String name, Future<Object?> Function() body) async {
try {
final result = await body();
_add(result == null ? name : '$name -> $result');
} catch (e) {
_add('$name failed: $e');
}
}
Future<void> _open() async {
await TnkPpiHybSdk.openOfferwall(
extraParams: _dark ? const {'theme': 'dark'} : null,
);
}
Future<void> _openPlacement() {
return Navigator.of(context)
.push(MaterialPageRoute<void>(builder: (_) => const PlacementPage()));
}
int get _id => int.tryParse(_appId.text) ?? 0;
Widget _button(String label, Future<Object?> Function() action) {
return FilledButton.tonal(
onPressed: () => _run(label, action),
child: Text(label),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('TNK PPI Hyb Example')),
body: LayoutBuilder(
key: const ValueKey<String>('home-body'),
builder: (context, constraints) {
final total = constraints.maxHeight;
final maxLog = (total * _logMaxShare)
.clamp(_logMinHeight, double.infinity)
.toDouble();
final logHeight = (_logHeight ?? total * _logDefaultShare)
.clamp(_logMinHeight, maxLog)
.toDouble();
return Column(
children: [
Expanded(
child: ListView(
padding: const EdgeInsets.all(12),
children: [
TextField(
controller: _userName,
decoration: const InputDecoration(labelText: 'User name'),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_button(
'setUserName',
() => TnkPpiHybSdk.setUserName(_userName.text),
),
_button('getUserName', TnkPpiHybSdk.getUserName),
_button(
'agree privacy',
() => TnkPpiHybSdk.setAgreePrivacy(true),
),
_button('isAgreePrivacy', TnkPpiHybSdk.isAgreePrivacy),
_button(
'revoke consent',
TnkPpiHybSdk.revokePrivacyConsent,
),
_button('COPPA on', () => TnkPpiHybSdk.setCOPPA(true)),
_button('GDPR 1', () => TnkPpiHybSdk.setGDPR(1)),
_button('getAdid', TnkPpiHybSdk.getAdid),
_button('refreshAdid', TnkPpiHybSdk.refreshAdid),
_button(
'ATT',
TnkPpiHybSdk.requestTrackingAuthorization,
),
],
),
const Divider(height: 24),
SwitchListTile(
title: const Text('Dark theme (extraParams)'),
value: _dark,
onChanged: (v) => setState(() => _dark = v),
),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton(
onPressed: () => _run('openOfferwall', _open),
child: const Text('Open offerwall'),
),
FilledButton(
onPressed: _openPlacement,
child: const Text('Placement'),
),
],
),
const SizedBox(height: 8),
TextField(
controller: _appId,
keyboardType: TextInputType.number,
decoration: const InputDecoration(labelText: 'Ad app ID'),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_button('adDetail', () => TnkPpiHybSdk.adDetail(_id)),
_button('adJoin', () => TnkPpiHybSdk.adJoin(_id)),
_button('adAction', () => TnkPpiHybSdk.adAction(_id)),
],
),
const Divider(height: 24),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_button('getTotalPoint', TnkPpiHybSdk.getTotalPoint),
_button(
'advertise point',
TnkPpiHybSdk.getAdvertiseTotalPoint,
),
_button(
'product point',
TnkPpiHybSdk.getProductTotalPoint,
),
_button(
'clearApiSession',
TnkPpiHybSdk.clearApiSession,
),
],
),
const Divider(height: 24),
TextField(
controller: _scheme,
decoration: const InputDecoration(labelText: 'Deep link'),
),
const SizedBox(height: 8),
_button(
'handleScheme',
() => TnkPpiHybSdk.handleScheme(_scheme.text),
),
],
),
),
Semantics(
label: 'Resize log',
child: GestureDetector(
key: const ValueKey<String>('log-resize-handle'),
behavior: HitTestBehavior.opaque,
onVerticalDragUpdate: (d) => setState(
() => _logHeight = ((_logHeight ?? logHeight) - d.delta.dy)
.clamp(_logMinHeight, maxLog),
),
child: Container(
height: _handleHeight,
width: double.infinity,
alignment: Alignment.center,
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest,
child: Container(
width: 36,
height: 4,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.outline,
borderRadius: BorderRadius.circular(2),
),
),
),
),
),
SizedBox(
key: const ValueKey<String>('log-panel'),
height: logHeight,
child: Container(
width: double.infinity,
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: _log.length,
itemBuilder: (_, i) => Text(
_log[i],
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
),
),
),
),
),
],
);
},
),
);
}
}