davianspace_hosting_flutter 1.0.3 copy "davianspace_hosting_flutter: ^1.0.3" to clipboard
davianspace_hosting_flutter: ^1.0.3 copied to clipboard

Enterprise-grade Flutter integration for DavianSpace hosting, connecting DI, lifecycle management, configuration, and logging to the widget tree.

example/lib/main.dart

// ignore_for_file: avoid_print // Example uses print for demonstration output.

/// Example demonstrating how to integrate `davianspace_hosting` with a
/// Flutter application using `davianspace_hosting_flutter`.
///
/// This file showcases three approaches:
///
/// 1. **Imperative** — `Host.runFlutterApp()`
/// 2. **Async imperative** — `Host.runFlutterAppAsync()`
/// 3. **Declarative** — `HostProvider` widget
library;

import 'package:davianspace_configuration/davianspace_configuration.dart';
import 'package:davianspace_dependencyinjection/davianspace_dependencyinjection.dart';
import 'package:davianspace_hosting/davianspace_hosting.dart';
import 'package:davianspace_hosting_flutter/davianspace_hosting_flutter.dart';
import 'package:flutter/material.dart';

// =============================================================================
// Domain services
// =============================================================================

/// A simple greeting service resolved via DI.
class GreetingService {
  const GreetingService(this.greeting);
  final String greeting;
}

/// A background [HostedService] that starts with the host.
class BackgroundWorker implements HostedService {
  @override
  Future<void> start() async {
    print('[BackgroundWorker] started');
  }

  @override
  Future<void> stop() async {
    print('[BackgroundWorker] stopped');
  }
}

// =============================================================================
// Host builder helper
// =============================================================================

/// Builds a configured [Host] with DI registrations and hosted services.
Future<Host> buildHost() async {
  return createDefaultBuilder()
      .configureServices((HostContext context, ServiceCollection services) {
    services.addInstance<GreetingService>(
      const GreetingService('Hello from DavianSpace DI!'),
    );
    services.addHostedService((_) => BackgroundWorker());
  }).build();
}

// =============================================================================
// Approach 1 — Imperative: Host.runFlutterApp()
// =============================================================================

/// The simplest approach: start the host and mount the widget tree in one call.
///
/// ```dart
/// void main() async {
///   final host = await buildHost();
///   await host.runFlutterApp(() => const MyApp());
/// }
/// ```
Future<void> imperativeMain() async {
  final host = await buildHost();

  await host.runFlutterApp(() => const MyApp());
}

// =============================================================================
// Approach 2 — Async imperative: Host.runFlutterAppAsync()
// =============================================================================

/// Displays a loading indicator while the host starts asynchronously.
///
/// ```dart
/// void main() async {
///   final host = await buildHost();
///   await host.runFlutterAppAsync(
///     () => const MyApp(),
///     loadingWidget: const MaterialApp(
///       home: Scaffold(body: Center(child: CircularProgressIndicator())),
///     ),
///   );
/// }
/// ```
Future<void> asyncImperativeMain() async {
  final host = await buildHost();

  await host.runFlutterAppAsync(
    () => const MyApp(),
    loadingWidget: const MaterialApp(
      home: Scaffold(body: Center(child: CircularProgressIndicator())),
    ),
    errorBuilder: (Object error) => MaterialApp(
      home: Scaffold(body: Center(child: Text('Startup error: $error'))),
    ),
  );
}

// =============================================================================
// Approach 3 — Declarative: HostProvider widget
// =============================================================================

/// Uses [HostProvider] in the widget tree for fully declarative lifecycle
/// management.
///
/// ```dart
/// void main() {
///   runApp(
///     HostProvider(
///       hostFactory: buildHost,
///       loadingBuilder: (_) => const MaterialApp(
///         home: Scaffold(body: Center(child: CircularProgressIndicator())),
///       ),
///       child: const MyApp(),
///     ),
///   );
/// }
/// ```
void declarativeMain() {
  runApp(
    HostProvider(
      hostFactory: buildHost,
      loadingBuilder: (_) => const MaterialApp(
        home: Scaffold(body: Center(child: CircularProgressIndicator())),
      ),
      errorBuilder: (_, Object error) => MaterialApp(
        home: Scaffold(body: Center(child: Text('Error: $error'))),
      ),
      child: const MyApp(),
    ),
  );
}

// =============================================================================
// Application widget
// =============================================================================

/// The root application widget that resolves services from the DI container
/// using [BuildContext] extensions.
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'DavianSpace Hosting Flutter',
      home: HomePage(),
    );
  }
}

/// A home page that resolves [GreetingService] from the widget tree.
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    // Resolve a required service — throws if not registered.
    final greeting = context.getService<GreetingService>();

    // Resolve an optional service — returns null if not registered.
    final maybeConfig = context.tryGetService<Configuration>();

    return Scaffold(
      appBar: AppBar(title: const Text('Hosting + Flutter')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(greeting.greeting, style: const TextStyle(fontSize: 24)),
            const SizedBox(height: 16),
            Text(
              maybeConfig != null ? 'Config present' : 'No config resolved',
              style: const TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}

// =============================================================================
// Entry point (pick one of the three approaches)
// =============================================================================

void main() => declarativeMain();
0
likes
160
points
95
downloads

Documentation

API reference

Publisher

verified publisherdavian.space

Weekly Downloads

Enterprise-grade Flutter integration for DavianSpace hosting, connecting DI, lifecycle management, configuration, and logging to the widget tree.

Repository (GitHub)
View/report issues
Contributing

Topics

#hosting #dependency-injection #flutter #architecture #lifecycle

License

MIT (license)

Dependencies

davianspace_configuration, davianspace_dependencyinjection, davianspace_hosting, davianspace_logging, flutter

More

Packages that depend on davianspace_hosting_flutter