I've found a very naive and easy approach for state management in flutter. I am storing the state using a hive box (a key value database) and rebuilding the screen at every second with setState.
The widget is not accessing an API. Just the hive database that is very fast and light weigh.
I guess that it is wrong but what is the problem with that approach in practice? Will that use lots of battery, too much CPU, cause crashes, memory leak? I don't think so.
Please, give a good reason not to do it.
late Box db;
main() async {
await Hive.initFlutter();
db = await Hive.openBox('db');
runApp(const MyApp());
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
Timer.periodic(const Duration(seconds: 1), (Timer t) => setState(() {}));
super.initState();
}
@override
Widget build(BuildContext context) {
double someValue = db.get('someValue', defaultValue: 0.0);
// Show someValue in a Text
}
CodePudding user response:
If you are new to flutter the question is seen as very logical and makes sense for the new developer so the sweet and simple answer is yes you can do this. But it's totally against the software development ethics and can make your app much slower than the average flutter app. The main concern during the development of any software especially a mobile app is that you have to think about the lower-end device that does not have good battery life and enough memory to run the most optimized application.
Conclusion
in some cases, you can use this method to periodically rebuild your flutter widget but always remember it will increase the chance of an unexpected crash and definitely will cause some UI lagging issues. for more insight, you can review your app performance with flutter Dart DevTools