💎DeepLink - Ki-Kobayashi/flutter_wiki GitHub Wiki
「app_links」をインストール
.
.
class MyApp extends ConsumerStatefulWidget {
const MyApp({super.key});
@override
ConsumerState<MyApp> createState() => _MyAppState();
}
class _MyAppState extends ConsumerState<MyApp> {
late AppLinks _appLinks;
StreamSubscription<Uri>? _uriLinkSubscription;
@override
void initState() {
super.initState();
_initDeepLinks();
ref.read(isOnlineProvider);
}
@override
void dispose() {
_uriLinkSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
・・・
}
Future<void> _initDeepLinks() async {
try {
_appLinks = AppLinks();
// アプリ終了しているか(コールド状態か)どうかを確認し、起動していれば初期リンクが返る
final appLink = await _appLinks.getInitialAppLink();
if (appLink != null) {
_openDeepLink(appLink);
}
// アプリ起動中(バックグラウンド含む)にあるときにリンク受信を待機し、届けば処理を実行する
_uriLinkSubscription = _appLinks.uriLinkStream.listen((uri) {
_openDeepLink(uri);
});
} on PlatformException {
// 初期URI受信失敗時に到達
logger.e("初期 URI の受信に失敗しました");
} on FormatException catch (err) {
if (!mounted) {
return;
}
// 初期URI:不正な形式で受信したときに到達
setState(() => _err = err);
}
}
/// DeepLink指定の画面を開く
void _openDeepLink(Uri uri) async {
final goRouter = ref.read(routerProvider);
final currentLocationPath = RouterPath.getCurrentLocationPath(ref: ref);
final itemId = _extractItemId(uri);
// 事前にキャッシュを消しておきたいProviderがあれば、ここか、指定画面を開いた後に、invalidateする
if (currentLocationPath == RouterPath.itemDetail) {
ref.invalidate(xxxxProvider(itemId));
}
// DeepLinkで指定画面を開く
await goRouter.push(RouterPath.itemDetail, extra: itemId);
}
/// PathからId抽出(バックエンド側で、itemIdを末尾に付与してリンクを送ってもらう)
String _extractItemId(Uri uri) {
List<String> pathSegments = uri.pathSegments;
return pathSegments.last;
}
}
.
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<!-- 👇DeepLink設定 -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- スキーマがhttp系だとAppではなく、ブラウザが立ち上がる -->
<data
android:scheme="service-name"
android:host="example.co.jp"
android:pathPattern="/item/.*" />
</intent-filter>
</activity>
.
.
.
.
.
.
.
.
.