moontraze_flutter 1.0.0 copy "moontraze_flutter: ^1.0.0" to clipboard
moontraze_flutter: ^1.0.0 copied to clipboard

Official Moontraze SDK for Flutter — Auth, Database, Storage, Notifications

example/lib/main.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:moontraze_flutter/moontraze_flutter.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Moontraze SDK Demo',
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
      ),
      home: const DemoPage(),
    );
  }
}

class DemoPage extends StatefulWidget {
  const DemoPage({super.key});

  @override
  State<DemoPage> createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  final _projectIdController = TextEditingController();
  final _apiKeyController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  MoonSDK? _moon;
  String _log = '';
  bool _loading = false;

  void _appendLog(String text) {
    setState(() {
      _log += '$text\n';
    });
  }

  void _initSdk() {
    if (_projectIdController.text.isEmpty || _apiKeyController.text.isEmpty) {
      _appendLog(' Project ID and API Key required');
      return;
    }

    setState(() {
      _moon = MoonSDK(MoonConfig(
        projectId: _projectIdController.text.trim(),
        apiKey: _apiKeyController.text.trim(),
      ));
      _log = '';
    });

    _appendLog(' SDK initialized');
  }

  Future<void> _register() async {
    if (_moon == null) {
      _appendLog(' Init SDK first');
      return;
    }

    setState(() => _loading = true);
    try {
      _appendLog('1️ Registering...');

      final email = _emailController.text.trim();
      final password = _passwordController.text;

      final result = await _moon!.auth.register(email, password, 'Flutter Test');

      _appendLog(' Registered: ${result['user']['id']}');

      _moon!.setToken(result['token']);

      // Create DB record
      _appendLog('2️ Creating DB record...');
      await _moon!.db.set('users/${result['user']['id']}', {
        'name': 'Flutter Test',
        'email': email,
        'platform': 'flutter',
      });
      _appendLog(' DB created');

      // Read
      _appendLog('3️ Reading DB record...');
      final user = await _moon!.db.get('users/${result['user']['id']}');
      _appendLog(' Read: $user');

      // Update
      _appendLog('4️ Updating field...');
      await _moon!.db.updateField(
        'users/${result['user']['id']}',
        'status',
        'active',
      );
      _appendLog(' Updated');

      _appendLog('\n All tests passed!');
    } catch (e) {
      _appendLog(' Error: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> _uploadFile() async {
    if (_moon == null) {
      _appendLog(' Init SDK first');
      return;
    }

    setState(() => _loading = true);
    try {
      _appendLog(' Uploading test file...');

      // Create test file
      final tempDir = Directory.systemTemp;
      final file = File('${tempDir.path}/test_${DateTime.now().millisecondsSinceEpoch}.txt');
      await file.writeAsString('Hello from Flutter SDK!');

      final result = await _moon!.storage.upload(file);

      _appendLog(' Uploaded: ${result['publicUrl']}');
      _appendLog('   ID: ${result['id']}');
      _appendLog('   Size: ${result['size']} bytes');

      // Get presigned URL
      _appendLog(' Getting presigned URL...');
      final presign = await _moon!.storage.getPresignedUrl(result['id']);
      _appendLog(' Presign expires in: ${presign['expiresIn']}s');

      // Delete
      _appendLog('  Deleting file...');
      await _moon!.storage.delete(result['id']);
      _appendLog(' Deleted');
    } catch (e) {
      _appendLog(' Error: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> _login() async {
    if (_moon == null) {
      _appendLog(' Init SDK first');
      return;
    }

    setState(() => _loading = true);
    try {
      _appendLog(' Logging in...');

      final result = await _moon!.auth.login(
        _emailController.text.trim(),
        _passwordController.text,
      );

      if (result['requiresTotp'] == true) {
        _appendLog('  TOTP required');
        _appendLog('   Login Ticket: ${result['loginTicket']}');
        return;
      }

      _moon!.setToken(result['token']);
      _appendLog('Logged in: ${result['user']['id']}');
    } catch (e) {
      _appendLog('Error: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Moontraze SDK Demo'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Init SDK Card
            _buildCard(
              title: '1. Initialize SDK',
              children: [
                TextField(
                  controller: _projectIdController,
                  decoration: const InputDecoration(
                    labelText: 'Project ID',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 8),
                TextField(
                  controller: _apiKeyController,
                  decoration: const InputDecoration(
                    labelText: 'API Key',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 8),
                ElevatedButton(
                  onPressed: _initSdk,
                  child: const Text('Initialize'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Auth Card
            _buildCard(
              title: '2. Register / Login',
              children: [
                TextField(
                  controller: _emailController,
                  decoration: const InputDecoration(
                    labelText: 'Email',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 8),
                TextField(
                  controller: _passwordController,
                  decoration: const InputDecoration(
                    labelText: 'Password',
                    border: OutlineInputBorder(),
                  ),
                  obscureText: true,
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _loading ? null : _register,
                        child: const Text('Register'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _loading ? null : _login,
                        child: const Text('Login'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Storage Card
            _buildCard(
              title: '3. Storage Test',
              children: [
                ElevatedButton.icon(
                  onPressed: _loading ? null : _uploadFile,
                  icon: const Icon(Icons.upload),
                  label: const Text('Upload + Delete File'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Log Card
            _buildCard(
              title: 'Log',
              children: [
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.black87,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    _log.isEmpty ? 'No output yet' : _log,
                    style: const TextStyle(
                      color: Colors.green,
                      fontFamily: 'monospace',
                      fontSize: 12,
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                if (_loading)
                  const Center(child: CircularProgressIndicator()),
                if (!_loading && _log.isNotEmpty)
                  TextButton(
                    onPressed: () => setState(() => _log = ''),
                    child: const Text('Clear Log'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCard({
    required String title,
    required List<Widget> children,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            ...children,
          ],
        ),
      ),
    );
  }
}
0
likes
140
points
--
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Official Moontraze SDK for Flutter — Auth, Database, Storage, Notifications

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, http, http_parser

More

Packages that depend on moontraze_flutter