Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

Is this Flutter (Dart) code robust re "async" usage or are futher null checks required?

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 
    }
}
question from:https://stackoverflow.com/questions/66058005/is-this-flutter-dart-code-robust-re-async-usage-or-are-futher-null-checks-re

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...