void main() async {
await Hive.initFlutter();
await Hive.openBox('settings');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo Settings',
home: Scaffold(
body: ValueListenableBuilder<Box>(
valueListenable: Hive.box('settings').listenable(),
builder: (context, box, widget) {
return Center(
child: Switch(
value: box.get('darkMode', defaultValue: false),
onChanged: (val) {
box.put('darkMode', val);
},
),
);
},
),
),
);
}
}
// Connectivity클래스 선언문
class Connectivity {
factory Connectivity() { //싱글톤이다.
if (_singleton == null) {
_singleton = Connectivity._();
}
return _singleton!;
}
Connectivity._();
static Connectivity? _singleton;
static ConnectivityPlatform get _platform => ConnectivityPlatform.instance;
// Stream으로 받기
Stream<ConnectivityResult> get onConnectivityChanged {
return _platform.onConnectivityChanged;
}
//현재상태를 비동기 객체로 받기
Future<ConnectivityResult> checkConnectivity() {
return _platform.checkConnectivity();
}
}
late Connectivity _connectivity;
late ConnectivityResult _result;
var box = await Hive.box('user');
Future<void> saveData(data) async {
_result = await _connectivity.checkConnectivity();
if(_result == ConnectivityResult.none) {
await box.put(data.key, data.value);
} else{
await saveToServer(data);
}
}