Is the following Flutter (using Flame package too) code robust in the sense that, is there a risk "prefs" may not be available during "update" and further checks and balances should be put in? Suggested code change to make it robust?
import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LightComponent extends SpriteComponent {
SharedPreferences prefs;
LightComponent() : super.fromImage(Vector2(404/4,406/4), Flame.images.fromCache('jupiter_404×406.png'),)
Future<void> onLoad() async {
prefs = await SharedPreferences.getInstance();
}
void render(Canvas c) {
super.render(c);
}
void update(double t) {
super.update(t);
bool showWindow = prefs.getBool('showWindow'); // <== IS THIS OK, OR IS THERE Pref == null potential issue to cover???
// etc
}
}
The engine waits for onLoad()
to be done before it adds the component to the update loop, so your code is the preferred way to do initialization of things that need to be loaded within components. So since update
won't be called on the component before onLoad()
has finished, your code should be safe without any extra checks inside of update
.