Home > Software engineering >  What should I do when I have to use "void function() async" as a last resort in Flutter?
What should I do when I have to use "void function() async" as a last resort in Flutter?

Time:10-02

My function is as follows:

void function() async {
  …
}

I used the above function in Widget build(BuildContext context).

Actually, I want it to be Future<void> function() async instead of void function() async.

However, I can't use await in Widget build(BuildContext context), so I can't use Future<void> function() async because Future requires await.

I shouldn't use FutureBuilder or then because I don't want to get the data in the function, I just want to run the function.

Appreciate if someone can advise. Thank you in advance!

CodePudding user response:

build method can run up to 60(maybe more with the newest phones)times per second, so it's not a good idea to run any heavy computation or API call in the build method. It's simply for building(widgets).

You may want to rethink your app architecture if you think you must.

Consider bloc pattern or just checkout other lifecycle methods for stateful widgets. This article has a list of them.

As for the question, async functions technically don't require you to await them. You can just call them without adding await in front of them.

If you have a warning, it might be coming from lint rules. Related rule.

CodePudding user response:

You can define your function as future & call it in initState of StatefulWidget (without await)

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

    Future<void> myFutureFunction() async {
      // some future work with
    }

  @override
  void initState() {
    super.initState();
    // this will be called once, when this widget is apear to the screen
    myFutureFunction();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox();
  }
}
  • Related