Skip to content

Why async method blocks Navigator.push ? #110159

@Fozei

Description

@Fozei

I am using Navigator.push method navigate to page B from page A.

In page B, I have a huge computation, which is convince to trigger it in initState method form logic, for sure it will block the rendering process if in sync. So I try to make it in async method.

I expect to seen the computation be triggered, the Navigator navigate smoothly and the page B rend normal(with a loading etc...).

But I see the program blocked, and will not navigate to page B until the async computation finished.

For demonstration, I make the huge compute just a huge for-loop.

Here is the code in initState:

 @override
  void initState() {
    super.initState();
    print("start call async method-------");

    // 1. block the router push
    // _byAsyncMethod();

    // 2. by Future,block the router push
    _byFuture().then((value) => print(value)).whenComplete(() => print("compute finish"));

    // 3. by Future API delay,no stuck,It is ok,but I want to put computation in async,how?
    // _byFutureApi().whenComplete(() => EasyLoading.dismiss());

    // 4. block the router push
    // Future.delayed(Duration.zero, () async {
    //   for (int i = 0; i < 10000; i++) {
    //     for (int j = 0; j < 10000; j++) {
    //       for (int k = 0; k < 50; k++) {}
    //     }
    //   }
    // });
    print("end call async method-------");
  }

Below are my codes, I tried kinds of different ways, but I can not achieve it .

1

  // will block the router push
  Future<void> _byAsyncMethod() async {
    for (int i = 0; i < 10000; i++) {
      for (int j = 0; j < 10000; j++) {
        for (int k = 0; k < 50; k++) {}
      }
    }
  }

2

// will block the router push
  Future<int> _byFuture() async {
    return Future(() {
      int num = 0;
      for (int i = 0; i < 10000; i++) {
        for (int j = 0; j < 10000; j++) {
          for (int k = 0; k < 50; k++) {
            num = k % 2;
          }
        }
      }
      return num;
    });
  }

3

// will not block, but how I can arrange my code in side ?
  Future<int> _byFutureApi() {
    return Future.delayed(const Duration(seconds: 3)).then((value) => Future.value(3));
  }

4

   // 4. block the router push
     Future.delayed(Duration.zero, () async {
       for (int i = 0; i < 10000; i++) {
         for (int j = 0; j < 10000; j++) {
           for (int k = 0; k < 50; k++) {}
         }
       }
     });

Below is my environments:

Flutter 3.0.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f1875d570e (6 周前) • 2022-07-13 11:24:16 -0700
Engine • revision e85ea0e79c
Tools • Dart 2.17.6 • DevTools 2.12.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    r: invalidIssue is closed as not valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions