0

3. Cài đặt nhận dữ liệu từ deeplink trên Flutter

Đây là service mình dùng để handle deeplink data:


class DeepLinkServices extends GetxController {
  DeepLinkServices._privateConstructor();

  static final DeepLinkServices _instance =
  DeepLinkServices._privateConstructor();

  static DeepLinkServices get instance => _instance;

  Uri? get initialLink => _initialLink;
  Uri? _initialLink;
  StreamSubscription<Uri>? _linkSubscription;
  bool _isInitialAppLinkHandled = false;

  @override
  void onInit() {
    super.onInit();
    initialize();
  }

  Future<void> initRoute() async {
    final appLinks = AppLinks();
    _initialLink = await appLinks.getInitialLink();
  }

  Future<void> initialize() async {
    final appLinks = AppLinks();
    Logger.i('[Deep Link]: initialize');

    // Check initial link if app was in cold state (terminated)
    if (!_isInitialAppLinkHandled) {
      _initialLink = await appLinks.getInitialLink();
      if (_initialLink != null) {
        _isInitialAppLinkHandled = true;
        _handleLinkData(_initialLink!);
      }
    }

    // Handle link when app is in warm state (foreground or background)
    _linkSubscription = appLinks.uriLinkStream.listen(
      _handleLinkData,
      onError: (err) {
        Logger.e('[Deep Link]: Fail $err');
      },
      onDone: () {
        _linkSubscription?.cancel();
      },
    );
  }

  @override
  void onClose() {
    _linkSubscription?.cancel();
    super.onClose();
  }

  /// Handles the link navigation Deep Links.
  void _handleLinkData(Uri uri) {
    Logger.i('[Deep Link] Handler: $uri');

    // Parse the URI and navigate based on path
    final parsedPath = _parsePath(uri);
    if (parsedPath != null) {
      _handleNavigation(parsedPath);
    }
  }

  /// Parses the URI path to determine the type and ID
  Map<String, String>? _parsePath(Uri uri) {
    if (uri.pathSegments.isNotEmpty) {
      if (uri.pathSegments[0] == 'product') {
        return {
          'type': 'product',
          'id': uri.pathSegments.last,
        };
      } else if (uri.pathSegments[0] == 'user') {
        return {
          'type': 'user',
          'id': uri.pathSegments.last,
        };
      }
    }
    return null;
  }

  /// Navigate based on parsed path
  void _handleNavigation(Map<String, String> parsedPath) {
    final type = parsedPath['type'];
    final id = parsedPath['id'];

    Logger.e('[Deep Link] type: $type = id: $id');
    if (type == 'product' && id != null) {
      navigatorKey.currentState?.context.navigateTo(
        RoutePath.requestProductScreen,
        routeSettings: RouteSettings(
          arguments: ProductInviteArgument(int.parse(id)),
        )
      );
    } else if (type == 'user' && id != null) {
      // Navigate to user screen
      final userModel = UserModel(userId: int.tryParse(id));
      navigatorKey.currentState?.context.navigateTo(
        RoutePath.userDetailScreen,
        routeSettings: RouteSettings(
          arguments: UserDetailArgument(userModel),
        ),
      );
    } else {
      Logger.e('[Deep Link] Unknown path: $type');
    }
  }
}

Ngoài file main.dart, init service này lên :

    await DeepLinkServices.instance.initRoute();

Vậy là xong, để điều hướng đi chỗ khác thì bn chỉnh lại code trong service đến trang mình cần.


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.