|
import 'package:flutter/material.dart'; |
|
import 'package:loon/loon.dart'; |
|
import 'package:shared_preferences/shared_preferences.dart'; |
|
|
|
void main() { |
|
runApp(const MyApp()); |
|
} |
|
|
|
class MyApp extends StatelessWidget { |
|
const MyApp({Key? key}) : super(key: key); |
|
|
|
@override |
|
Widget build(BuildContext context) { |
|
return const MaterialApp( |
|
title: 'Loon/SharedPreferences Conflict Demo', |
|
home: MyHomePage(), |
|
); |
|
} |
|
} |
|
|
|
class MyHomePage extends StatefulWidget { |
|
const MyHomePage({Key? key}) : super(key: key); |
|
|
|
@override |
|
State<MyHomePage> createState() => _MyHomePageState(); |
|
} |
|
|
|
class _MyHomePageState extends State<MyHomePage> { |
|
String _savedValue = 'No Value Saved'; |
|
String _loonStatus = 'Loon Not Initialized'; |
|
late SharedPreferences _prefs; |
|
|
|
// Function to initialize SharedPreferences and Loon |
|
Future<void> _initializePrefsAndLoon() async { |
|
setState(() { |
|
_loonStatus = 'Initializing...'; |
|
}); |
|
|
|
try { |
|
// Initialize SharedPreferences |
|
_prefs = await SharedPreferences.getInstance(); |
|
|
|
// Configure Loon |
|
Loon.configure( |
|
persistor: |
|
Persistor.current(settings: PersistorSettings(encrypted: false)), |
|
); |
|
|
|
// Attempt to hydrate Loon |
|
Loon.hydrate(); |
|
|
|
setState(() { |
|
_loonStatus = 'Loon Initialized Successfully'; |
|
_loadSavedValue(); // Load value after Loon initialization |
|
}); |
|
} catch (e) { |
|
setState(() { |
|
_loonStatus = 'Error Initializing Loon: $e'; |
|
}); |
|
print('Error initializing Loon: $e'); // Log the error |
|
} |
|
} |
|
|
|
void _loadSavedValue() { |
|
setState(() { |
|
_savedValue = _prefs.getString('myKey') ?? 'No Value Saved'; |
|
}); |
|
} |
|
|
|
void _saveValue(String value) async { |
|
if (_prefs == null) { |
|
// Handle the case where SharedPreferences might not be initialized |
|
print( |
|
"SharedPreferences is not initialized. Please initialize Loon and SharedPreferences first."); |
|
return; |
|
} |
|
await _prefs.setString('myKey', value); |
|
Loon.collection('test').doc('test').createOrUpdate({'myKey': value}); |
|
_loadSavedValue(); |
|
} |
|
|
|
@override |
|
Widget build(BuildContext context) { |
|
return Scaffold( |
|
appBar: AppBar( |
|
title: const Text('Conflict Demo'), |
|
), |
|
body: Center( |
|
child: Column( |
|
mainAxisAlignment: MainAxisAlignment.center, |
|
children: <Widget>[ |
|
Text('Saved Value: $_savedValue'), |
|
const SizedBox(height: 20), |
|
Text('Loon Status: $_loonStatus'), |
|
const SizedBox(height: 20), |
|
ElevatedButton( |
|
onPressed: _initializePrefsAndLoon, |
|
child: const Text('Initialize Loon and SharedPreferences'), |
|
), |
|
const SizedBox(height: 20), |
|
ElevatedButton( |
|
onPressed: () => _saveValue('Hello from SharedPreferences!'), |
|
child: const Text('Save Value'), |
|
), |
|
], |
|
), |
|
), |
|
); |
|
} |
|
} |