Skip to content

LDK Core Class

The LDK class is the main entry point for the Lazy Development Kit. It provides a singleton pattern for managing all SDK services and features.

Class Overview

class LDK {
  // Singleton instance
  static LDK get instance;

  // Initialization
  static Future<void> initialize({...});

  // Service accessors
  LDKAuth get auth;
  LDKStorage get storage;
  LDKGraphQLClient get graphql;
  LDKIntelligentCache get cache;
  LDKRealtime get realtime;
  LDKOfflineStorage get offlineStorage;
  LDKEnhancedAuth get enhancedAuth;

  // Factory methods
  static LDKCollection collection(String collectionName);

  // Utility methods
  static Future<Map<String, List<Map<String, dynamic>>>> globalSearch(...);
  static void setAuthToken(String token);
  static void clearAuthToken();
  static Future<void> dispose();
}

Static Methods

initialize

Initializes the LDK SDK with the specified configuration.

static Future<void> initialize({
  required String baseUrl,
  String? authToken,
  bool enableLogging = false,
  Duration? connectTimeout,
  Duration? receiveTimeout,
  bool enableGraphQL = true,
  bool enableRealtime = true,
  bool enableOfflineStorage = true,
  bool enableIntelligentCache = true,
  bool enableEnhancedAuth = true,
  Map<String, dynamic>? cacheConfig,
})

Parameters

Parameter Type Default Description
baseUrl String Required The base URL of your Strapi server
authToken String? null Initial JWT authentication token
enableLogging bool false Enable HTTP request/response logging
connectTimeout Duration? 30s Connection timeout duration
receiveTimeout Duration? 30s Response timeout duration
enableGraphQL bool true Enable GraphQL client
enableRealtime bool true Enable real-time WebSocket features
enableOfflineStorage bool true Enable offline data persistence
enableIntelligentCache bool true Enable intelligent caching system
enableEnhancedAuth bool true Enable enhanced authentication features
cacheConfig Map<String, dynamic>? null Cache configuration strategies

Example

await LDK.initialize(
  baseUrl: 'https://your-strapi-server.com',
  authToken: 'your-jwt-token',
  enableLogging: true,
  connectTimeout: Duration(seconds: 30),
  enableGraphQL: true,
  enableRealtime: true,
  cacheConfig: {
    'strategies': {
      'posts': {
        'ttl': 300000, // 5 minutes
        'maxSize': 100,
        'evictionPolicy': 'lru',
      },
    },
  },
);

Throws

  • LDKConfigurationException - If configuration is invalid
  • LDKServerException - If server connection fails

collection

Creates a collection reference for CRUD operations.

static LDKCollection collection(String collectionName)

Parameters

Parameter Type Description
collectionName String Name of the Strapi collection

Returns

Returns LDKEnhancedCollection if V2 features are enabled, otherwise LDKCollection.

Example

final posts = LDK.collection('posts');
final users = LDK.collection('users');

// Enhanced collection with V2 features
final enhancedPosts = LDK.collection('posts') as LDKEnhancedCollection;

globalSearch

Performs a search across multiple collections simultaneously.

static Future<Map<String, List<Map<String, dynamic>>>> globalSearch(
  String searchTerm, {
  List<String>? collections,
  List<String>? searchFields,
  int? limit,
})

Parameters

Parameter Type Description
searchTerm String The search query
collections List<String>? Collections to search (default: ['posts', 'pages', 'articles'])
searchFields List<String>? Fields to search in
limit int? Maximum results per collection

Returns

Map where keys are collection names and values are search results.

Example

final results = await LDK.globalSearch(
  'flutter development',
  collections: ['posts', 'tutorials', 'docs'],
  searchFields: ['title', 'content', 'tags'],
  limit: 10,
);

// Access results
final posts = results['posts'] ?? [];
final tutorials = results['tutorials'] ?? [];

setAuthToken

Updates the authentication token for all requests.

static void setAuthToken(String token)

Example

// After user login
final user = await LDK.instance.auth.signIn(email: email, password: password);
LDK.setAuthToken(user.jwt);

clearAuthToken

Removes the authentication token from all requests.

static void clearAuthToken()

Example

// On user logout
await LDK.instance.auth.signOut();
LDK.clearAuthToken();

dispose

Disposes all resources and resets the SDK instance.

static Future<void> dispose()

Example

// Clean up when app is closing
await LDK.dispose();

Instance Properties

instance

Gets the singleton instance of LDK.

static LDK get instance

Example

final ldk = LDK.instance;
if (ldk.isInitialized) {
  // SDK is ready to use
}

isInitialized

Checks if the SDK has been initialized.

bool get isInitialized

Example

if (LDK.instance.isInitialized) {
  final posts = LDK.collection('posts');
} else {
  await LDK.initialize(baseUrl: 'https://api.example.com');
}

Service Accessors

auth

Gets the authentication service.

LDKAuth get auth

Example

final auth = LDK.instance.auth;
final user = await auth.signIn(email: 'user@example.com', password: 'password');

Throws

  • LDKConfigurationException - If SDK not initialized

storage

Gets the storage service for file operations.

LDKStorage get storage

Example

final storage = LDK.instance.storage;
final uploadedFile = await storage.uploadFile(file);

graphql

Gets the GraphQL client (V2 feature).

LDKGraphQLClient get graphql

Example

try {
  final graphql = LDK.instance.graphql;
  final result = await graphql.query('{ posts { id title } }');
} catch (e) {
  // GraphQL not enabled
  print('GraphQL not available: $e');
}

Throws

  • LDKConfigurationException - If GraphQL not enabled

cache

Gets the intelligent cache service (V2 feature).

LDKIntelligentCache get cache

Example

try {
  final cache = LDK.instance.cache;
  await cache.invalidateCollection('posts');
} catch (e) {
  // Cache not enabled
}

realtime

Gets the real-time service (V2 feature).

LDKRealtime get realtime

Example

try {
  final realtime = LDK.instance.realtime;
  realtime.subscribeToCollection('posts').listen((event) {
    print('Post updated: ${event.data}');
  });
} catch (e) {
  // Real-time not enabled
}

offlineStorage

Gets the offline storage service (V2 feature).

LDKOfflineStorage get offlineStorage

Example

try {
  final offline = LDK.instance.offlineStorage;
  offline.isOnlineStream.listen((isOnline) {
    print('Connection status: ${isOnline ? 'Online' : 'Offline'}');
  });
} catch (e) {
  // Offline storage not enabled
}

enhancedAuth

Gets the enhanced authentication service (V2 feature).

LDKEnhancedAuth get enhancedAuth

Example

try {
  final enhancedAuth = LDK.instance.enhancedAuth;
  await enhancedAuth.enableBiometric();
} catch (e) {
  // Enhanced auth not enabled
}

Usage Patterns

Basic Initialization and Usage

import 'package:ldk/ldk.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initializeLDK();
  }

  Future<void> _initializeLDK() async {
    try {
      await LDK.initialize(
        baseUrl: 'https://your-strapi-server.com',
        enableLogging: true,
      );

      // SDK is ready
      setState(() {});
    } catch (e) {
      print('Failed to initialize LDK: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!LDK.instance.isInitialized) {
      return CircularProgressIndicator();
    }

    return MaterialApp(
      home: HomePage(),
    );
  }

  @override
  void dispose() {
    LDK.dispose();
    super.dispose();
  }
}

Feature Detection

class FeatureService {
  static bool get hasGraphQL {
    try {
      LDK.instance.graphql;
      return true;
    } catch (e) {
      return false;
    }
  }

  static bool get hasRealtime {
    try {
      LDK.instance.realtime;
      return true;
    } catch (e) {
      return false;
    }
  }

  static bool get hasCache {
    try {
      LDK.instance.cache;
      return true;
    } catch (e) {
      return false;
    }
  }
}

Error Handling

class LDKService {
  static Future<void> initializeWithRetry({
    required String baseUrl,
    int maxRetries = 3,
  }) async {
    for (int i = 0; i < maxRetries; i++) {
      try {
        await LDK.initialize(baseUrl: baseUrl);
        return; // Success
      } catch (e) {
        if (i == maxRetries - 1) rethrow; // Last attempt failed

        // Wait before retry
        await Future.delayed(Duration(seconds: 2 * (i + 1)));
      }
    }
  }
}

Best Practices

1. Initialize Early

Initialize LDK as early as possible in your app lifecycle:

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

  await LDK.initialize(
    baseUrl: 'https://your-server.com',
  );

  runApp(MyApp());
}

2. Handle Initialization Errors

Always handle initialization errors gracefully:

try {
  await LDK.initialize(baseUrl: serverUrl);
} on LDKConfigurationException catch (e) {
  // Configuration error - fix your setup
  print('Configuration error: $e');
} on LDKServerException catch (e) {
  // Server error - maybe retry or show offline mode
  print('Server error: $e');
} catch (e) {
  // Other errors
  print('Unexpected error: $e');
}

3. Feature-Based Development

Build your app to gracefully handle missing features:

Widget buildPostList() {
  if (FeatureService.hasRealtime) {
    // Use real-time updates
    return StreamBuilder(
      stream: LDK.collection('posts').subscribeToUpdates(),
      builder: (context, snapshot) => ...,
    );
  } else {
    // Use traditional polling
    return FutureBuilder(
      future: LDK.collection('posts').get(),
      builder: (context, snapshot) => ...,
    );
  }
}

4. Proper Cleanup

Always dispose of resources when done:

class MyService {
  StreamSubscription? _subscription;

  void startListening() {
    if (FeatureService.hasRealtime) {
      _subscription = LDK.instance.realtime
          .subscribeToCollection('posts')
          .listen(_handleUpdate);
    }
  }

  void dispose() {
    _subscription?.cancel();
  }
}

See Also


Next: Authentication API →