Skip to main content

flutter_deep_link_router 1.0.1 copy "flutter_deep_link_router: ^1.0.1" to clipboard
flutter_deep_link_router: ^1.0.1 copied to clipboard

A robust deep linking and navigation middleware for Flutter. Handles URI parsing, guarded routes, cold-start restoration, and link previews.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_deep_link_router/flutter_deep_link_router.dart';
import 'package:go_router/go_router.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 1. Define Authentication State Simulation
  bool isAuthenticated = false;

  // 2. Define Routes
  final routes = [
    RouteDefinition(
      path: '/',
      name: 'home',
      builder: (context) => const HomeScreen(),
    ),
    RouteDefinition(
      path: '/dashboard',
      name: 'dashboard',
      guards: [
        AuthGuard(
          isAuthenticated: () async => isAuthenticated,
          redirectPath: '/login',
        ),
      ],
      builder: (context) => const DashboardScreen(),
    ),
    RouteDefinition(
      path: '/login',
      name: 'login',
      builder: (context) => LoginScreen(onLogin: () => isAuthenticated = true),
    ),
    RouteDefinition(
      path: '/product/:id',
      metadata: const RouteMetadata(
        title: 'Premium Product',
        description: 'Detail view of our best product.',
        imageUrl: 'https://placeholder.com/150',
      ),
      builder: (context) => const ProductDetailScreen(),
    ),
  ];

  // 3. Setup GoRouter
  final goRouter = GoRouter(
    routes: [
      GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
      GoRoute(
          path: '/dashboard',
          builder: (context, state) => const DashboardScreen()),
      GoRoute(
          path: '/login',
          builder: (context, state) =>
              LoginScreen(onLogin: () => isAuthenticated = true)),
      GoRoute(
          path: '/product/:id',
          builder: (context, state) => const ProductDetailScreen()),
      GoRoute(
          path: '/404',
          builder: (context, state) =>
              const Scaffold(body: Center(child: Text('404')))),
    ],
  );

  // 4. Initialize DeepLinkRouter with GoRouter delegate
  final router = DeepLinkRouter(
    routes: routes,
    delegate: DeepLinkGoRouterDelegate(goRouter),
    parser: const DeepLinkParser(
      schemes: ['myapp', 'https'],
      hosts: ['myapp.com'],
    ),
  );

  // Simulate a cold start link
  // (In real use, this happens automatically or via handleColdStart)
  (router.coldStartHandler as DefaultColdStartHandler).setInitialLink(
    DeepLink.fromString('myapp://product/888'),
  );

  await router.handleColdStart();

  runApp(MyApp(router: router, goRouter: goRouter));
}

class MyApp extends StatelessWidget {
  final DeepLinkRouter router;
  final GoRouter goRouter;

  const MyApp({super.key, required this.router, required this.goRouter});

  @override
  Widget build(BuildContext context) {
    return DeepLinkObserver(
      router: router,
      onLinkReceived: (link) => print('Link Received: ${link.uri}'),
      onLinkBlocked: (event) => print(
          'Link Blocked by ${event.blockedBy}, redirected to ${event.redirectedTo}'),
      child: MaterialApp.router(
        title: 'Deep Link Router Demo',
        theme: ThemeData(
          useMaterial3: true,
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        ),
        routerConfig: goRouter,
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => context.push('/dashboard'),
              child: const Text('Go to Dashboard (Guarded)'),
            ),
            const SizedBox(height: 20),
            const DeepLinkPreviewDemo(),
          ],
        ),
      ),
    );
  }
}

class DeepLinkPreviewDemo extends StatelessWidget {
  const DeepLinkPreviewDemo({super.key});

  @override
  Widget build(BuildContext context) {
    // In actual app, router would be available via DI or context
    final router = (context.findAncestorWidgetOfExactType<MyApp>())!.router;

    return DeepLinkPreview(
      uri: 'myapp://product/456',
      router: router,
      builder: (context, metadata) => Card(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              const Text('Link Preview:',
                  style: TextStyle(fontWeight: FontWeight.bold)),
              Text(metadata?.title ?? 'Product Not Found'),
              Text(metadata?.description ?? ''),
            ],
          ),
        ),
      ),
    );
  }
}

class DashboardScreen extends StatelessWidget {
  const DashboardScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dashboard')),
      body: const Center(child: Text('Welcome to your private dashboard!')),
    );
  }
}

class LoginScreen extends StatelessWidget {
  final VoidCallback onLogin;
  const LoginScreen({super.key, required this.onLogin});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Login')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            onLogin();
            context.pop();
          },
          child: const Text('Login'),
        ),
      ),
    );
  }
}

class ProductDetailScreen extends StatelessWidget {
  const ProductDetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Product Detail')),
      body: const Center(child: Text('Displaying details for product...')),
    );
  }
}
1
likes
130
points
47
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A robust deep linking and navigation middleware for Flutter. Handles URI parsing, guarded routes, cold-start restoration, and link previews.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, go_router, path_to_regexp, provider

More

Packages that depend on flutter_deep_link_router