Created
October 21, 2020 08:55
-
-
Save cerberodev/879e3c203893042e53cedf804ecd70ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:hive/hive.dart'; | |
import 'package:hive_flutter/hive_flutter.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
const darkModeBox = 'darkModeTutorial'; | |
void main() async { | |
await Hive.initFlutter(); | |
await Hive.openBox(darkModeBox); | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
@override | |
_MyAppState createState() => _MyAppState(); | |
} | |
class _MyAppState extends State<MyApp> { | |
Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); | |
Future<int> _counter; | |
Future<void> _incrementCounter() async { | |
final SharedPreferences prefs = await _prefs; | |
final int counter = (prefs.getInt('counter') ?? 0) + 1; | |
setState(() { | |
_counter = prefs.setInt("counter", counter).then((bool success) { | |
return counter; | |
}); | |
}); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
_counter = _prefs.then((SharedPreferences prefs) { | |
return (prefs.getInt('counter') ?? 0); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return ValueListenableBuilder( | |
valueListenable: Hive.box(darkModeBox).listenable(), | |
builder: (context, box, widget) { | |
var darkMode = box.get('darkMode', defaultValue: false); | |
return MaterialApp( | |
themeMode: darkMode ? ThemeMode.dark : ThemeMode.light, | |
darkTheme: ThemeData.dark(), | |
home: Scaffold( | |
appBar: AppBar( | |
actions: [ | |
Switch( | |
value: darkMode, | |
onChanged: (val) { | |
box.put('darkMode', !darkMode); | |
}, | |
), | |
], | |
), | |
body: Center( | |
child: FutureBuilder( | |
future: _counter, | |
builder: (_, AsyncSnapshot<int> snapshot) { | |
switch (snapshot.connectionState) { | |
case ConnectionState.waiting: | |
return const CircularProgressIndicator(); | |
default: | |
if (snapshot.hasError) { | |
return Text('Error: ${snapshot.error}'); | |
} else { | |
return Text( | |
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n' | |
'This should persist across restarts.', | |
); | |
} | |
} | |
}, | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: _incrementCounter, | |
tooltip: 'Increment', | |
child: Icon(Icons.add), | |
), | |
), | |
); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment