/
main.dart
281 lines (256 loc) · 8.06 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uni_links/uni_links.dart';
bool _initialUriIsHandled = false;
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
Uri? _initialUri;
Uri? _latestUri;
Object? _err;
StreamSubscription? _sub;
final _scaffoldKey = GlobalKey();
final _cmds = getCmds();
final _cmdStyle = const TextStyle(
fontFamily: 'Courier', fontSize: 12.0, fontWeight: FontWeight.w700);
@override
void initState() {
super.initState();
_handleIncomingLinks();
_handleInitialUri();
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
/// Handle incoming links - the ones that the app will recieve from the OS
/// while already started.
void _handleIncomingLinks() {
if (!kIsWeb) {
// It will handle app links while the app is already started - be it in
// the foreground or in the background.
_sub = uriLinkStream.listen((Uri? uri) {
if (!mounted) return;
print('got uri: $uri');
setState(() {
_latestUri = uri;
_err = null;
});
}, onError: (Object err) {
if (!mounted) return;
print('got err: $err');
setState(() {
_latestUri = null;
if (err is FormatException) {
_err = err;
} else {
_err = null;
}
});
});
}
}
/// Handle the initial Uri - the one the app was started with
///
/// **ATTENTION**: `getInitialLink`/`getInitialUri` should be handled
/// ONLY ONCE in your app's lifetime, since it is not meant to change
/// throughout your app's life.
///
/// We handle all exceptions, since it is called from initState.
Future<void> _handleInitialUri() async {
// In this example app this is an almost useless guard, but it is here to
// show we are not going to call getInitialUri multiple times, even if this
// was a weidget that will be disposed of (ex. a navigation route change).
if (!_initialUriIsHandled) {
_initialUriIsHandled = true;
_showSnackBar('_handleInitialUri called');
try {
final uri = await getInitialUri();
if (uri == null) {
print('no initial uri');
} else {
print('got initial uri: $uri');
}
if (!mounted) return;
setState(() => _initialUri = uri);
} on PlatformException {
// Platform messages may fail but we ignore the exception
print('falied to get initial uri');
} on FormatException catch (err) {
if (!mounted) return;
print('malformed initial uri');
setState(() => _err = err);
}
}
}
@override
Widget build(BuildContext context) {
final queryParams = _latestUri?.queryParametersAll.entries.toList();
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('uni_links example app'),
),
body: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
children: [
if (_err != null)
ListTile(
title: const Text('Error', style: TextStyle(color: Colors.red)),
subtitle: Text('$_err'),
),
ListTile(
title: const Text('Initial Uri'),
subtitle: Text('$_initialUri'),
),
if (!kIsWeb) ...[
ListTile(
title: const Text('Latest Uri'),
subtitle: Text('$_latestUri'),
),
ListTile(
title: const Text('Latest Uri (path)'),
subtitle: Text('${_latestUri?.path}'),
),
ExpansionTile(
initiallyExpanded: true,
title: const Text('Latest Uri (query parameters)'),
children: queryParams == null
? const [ListTile(dense: true, title: Text('null'))]
: [
for (final item in queryParams)
ListTile(
title: Text(item.key),
trailing: Text(item.value.join(', ')),
)
],
),
],
_cmdsCard(_cmds),
const Divider(),
if (!kIsWeb)
ListTile(
leading: const Icon(Icons.error, color: Colors.red),
title: const Text(
'Force quit this example app',
style: TextStyle(color: Colors.red),
),
onTap: () {
// WARNING: DO NOT USE this in production !!!
// Your app will (most probably) be rejected !!!
if (Platform.isIOS) {
exit(0);
} else {
SystemNavigator.pop();
}
},
),
],
),
);
}
Widget _cmdsCard(List<String>? commands) {
Widget platformCmds;
if (commands == null) {
platformCmds = const Center(child: Text('Unsupported platform'));
} else {
platformCmds = Column(
children: [
const [
if (kIsWeb)
Text('Append this path to the Web app\'s URL, replacing `#/`:\n')
else
Text('To populate above fields open a terminal shell and run:\n'),
],
intersperse(
commands.map<Widget>((cmd) => InkWell(
onTap: () => _printAndCopy(cmd),
child: Text('\n$cmd\n', style: _cmdStyle),
)),
const Text('or')),
[
Text(
'(tap on any of the above commands to print it to'
' the console/logger and copy to the device clipboard.)',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.caption,
),
]
].expand((el) => el).toList(),
);
}
return Card(
margin: const EdgeInsets.only(top: 20.0),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: platformCmds,
),
);
}
Future<void> _printAndCopy(String cmd) async {
print(cmd);
await Clipboard.setData(ClipboardData(text: cmd));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Copied to Clipboard')),
);
}
void _showSnackBar(String msg) {
WidgetsBinding.instance?.addPostFrameCallback((_) {
final context = _scaffoldKey.currentContext;
if (context != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(msg),
));
}
});
}
}
List<String>? getCmds() {
late final String cmd;
var cmdSuffix = '';
const plainPath = 'path/subpath';
const args = 'path/portion/?uid=123&token=abc';
const emojiArgs =
'?arr%5b%5d=123&arr%5b%5d=abc&addr=1%20Nowhere%20Rd&addr=Rand%20City%F0%9F%98%82';
if (kIsWeb) {
return [
plainPath,
args,
emojiArgs,
// Cannot create malformed url, since the browser will ensure it is valid
];
}
if (Platform.isIOS) {
cmd = '/usr/bin/xcrun simctl openurl booted';
} else if (Platform.isAndroid) {
cmd = '\$ANDROID_HOME/platform-tools/adb shell \'am start'
' -a android.intent.action.VIEW'
' -c android.intent.category.BROWSABLE -d';
cmdSuffix = "'";
} else {
return null;
}
// https://orchid-forgery.glitch.me/mobile/redirect/
return [
'$cmd "unilinks://host/$plainPath"$cmdSuffix',
'$cmd "unilinks://example.com/$args"$cmdSuffix',
'$cmd "unilinks://example.com/$emojiArgs"$cmdSuffix',
'$cmd "unilinks://@@malformed.invalid.url/path?"$cmdSuffix',
];
}
List<Widget> intersperse(Iterable<Widget> list, Widget item) {
final initialValue = <Widget>[];
return list.fold(initialValue, (all, el) {
if (all.isNotEmpty) all.add(item);
all.add(el);
return all;
});
}