text:
Gallery example app crashes on launch, dependent dylib '@rpath/Flutter.framework/Flutter'

Reproduction Steps:
Reproducing on master and stable.
Delete any previous versions of Flutter Gallery from the device.
$ cd dev/integration_tests/flutter_gallery
$ flutter clean
$ git clean -dfX
$ rm -rf ~/Library/Developer/Xcode/DerivedData/*
$ flutter run --debug

App crashes on launch, flutter stuck on Application launched on the device. Waiting for observatory port.
Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Description: DYLD, dependent dylib '@rpath/Flutter.framework/Flutter' not found for '/private/var/containers/Bundle/Application/C582E1E9-F19B-4E9C-9C03-2F0CBA1132F7/Flutter Gallery.app/Flutter Gallery'. vm_copy() failure
Highlighted by Thread:  0

Flutter Gallery  5-13-20, 6-45 PM.crash.log
However, subsequent launches of the app (launching it manually on the phone) do not crash!
Flutter.framework is being copied to the normal Flutter Gallery.app/Frameworks spot.  @rpath looks correct:
$ otool -l build/ios/iphoneos/Flutter\ Gallery.app/Flutter\ Gallery
...
          cmd LC_LOAD_DYLIB
      cmdsize 64
         name @rpath/Flutter.framework/Flutter (offset 24)
   time stamp 2 Wed Dec 31 16:00:02 1969
      current version 0.0.0
compatibility version 0.0.0
Load command 14
...
          cmd LC_RPATH
      cmdsize 40
         path @executable_path/Frameworks (offset 12)
Load command 28
          cmd LC_RPATH
      cmdsize 40
         path @loader_path/Frameworks (offset 12)
Load command 29
          cmd LC_RPATH
      cmdsize 40
         path @executable_path/Frameworks (offset 12)
Load command 30

otool.log
It's getting copied during install:
[        ] [  7%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/ to device
[        ] [  7%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/_CodeSignature/ to device
[        ] [  7%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/_CodeSignature/CodeResources to device
[        ] [  7%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/icudtl.dat to device
[ +141 ms] [  8%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/Flutter to device
[ +805 ms] [ 13%] Copying /Users/m/Projects/flutter/dev/integration_tests/flutter_gallery/build/ios/iphoneos/Flutter Gallery.app/Frameworks/Flutter.framework/Info.plist to device

run.log (this log is from trying to repro the driver test but a normal flutter run has the same install logs)
Device log when it crashes is complaining about a Bad file descriptor:
	default	19:40:29.639013-0700	debugserver	1 +0.000000 sec [04d1/0407]: Disabling breakpoints and watchpoints, and detaching from 1234.
	default	19:40:29.639192-0700	debugserver	2 +0.000091 sec [04d1/0407]: error: ::ptrace (request = PT_THUPDATE, pid = 0x04d2, tid = 0x4b03, signal = -1) err = Invalid argument (0x00000016)
	default	19:40:29.639238-0700	debugserver	3 +0.000358 sec [04d1/1907]: error: ::read ( -1, 0x16d7deb08, 1024 ) => -1 err = Bad file descriptor (0x00000009)
	default	19:40:29.639270-0700	debugserver	Exiting.
com.apple.runningboard	default	19:40:29.639746-0700	runningboardd	[executable<debugserver>:1233] Death sentinel fired!
com.apple.runningboard	default	19:40:29.640290-0700	runningboardd	[application<io.flutter.examples.gallery>:1234] Death sentinel fired!
com.apple.runningboard	default	19:40:29.643165-0700	runningboardd	XPC connection invalidated: [executable<debugserver>:1233]

It's reproducing on:

flutter-devicelab-mac-11 Xcode 11.0/iPhone 4s 32-bit iOS 9.3.6 in the flutter_gallery_ios32__transition_perf test
flutter-devicelab-mac-1 Xcode 11.3/iPhone 6s iOS 13.1.3 in the flutter_gallery_ios__transition_perf test
On my machine Xcode 4 and Xcode 11.5 beta 2 iPhone 6s iOS 13.4.1.

[✓] Flutter (Channel master, 1.19.0-2.0.pre.21, on Mac OS X 10.15.4 19E266, locale en-US)
    • Flutter version 1.19.0-2.0.pre.21 at /Users/m/Projects/flutter
    • Framework revision 7f400af35a (2 days ago), 2020-05-12 07:35:02 -0700
    • Engine revision 156970a248
    • Dart version 2.9.0 (build 2.9.0-8.0.dev 4e520824f5)

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
    • Xcode at /Users/m/Applications/Xcode-11-5-beta2.app/Contents/Developer
    • Xcode 11.5, Build version 11N605f
    • CocoaPods version 1.9.0

The biggest head-scratcher here is that it doesn't crash on the second launch.  So it is getting embedded to the right path, dyld is eventually happy, but just not when the debugger launches it?

Are you sure the architecture of the library you are trying to load is correct?  Sometimes binaries are trimmed to just one architecture for debug builds.

It repros in profile and release, and it wouldn't link at all during the host build if the architectures weren't correct.

Faster reproduction steps:
$ flutter create test_link
$ cd test_link

Copy the flutter_gallery's dependencies to the pubspect.yaml
$ flutter build ios --debug

Now, you can run this over and over to reproduce:
$ <flutter>/bin/cache/artifacts/ios-deploy/ios-deploy --id <device-id> --bundle build/ios/iphoneos/Runner.app --no-wifi --uninstall --justlaunch

Notes:

I was able to reproduce this on v1.12.13-hotfixes, so this isn't a recent regression.
I ran the above ios-deploy command on my machine with the iPhone 6s and it crashed 4 of 20 times.
If I don't copy over the flutter_gallery's dependencies it never crashes.  So a fresh flutter create app doesn't crash.
ios-deploy with --noninteractive (launch debugger and wait) instead of --justlaunch (launch debugger and quit) also never crashes.
This manifests to the user as the tool being stuck waiting for the observatory if they don't notice that the app launched and immediately crashed since the tool doesn't have the capacity to capture crash logs at the moment.  So how many "discovery" issues are really just this?

My guess is that there's a race between the ios-deploy AMDeviceSecureInstall call being complete and all files being copied to their final location on disk on device.  I wasn't able to reproduce this without copying over the flutter_gallery dependencies, which makes me think it crossed some size threshold on my particular devices that made it start to manifest.
flutter_gallery_ios32__transition_perf may be particularly flaky because the older iPhone 4s has slower I/O.  I don't know why this started manifesting in the devicelab in the last week.

The device sure thinks it's fully installed before the crash, so I don't know what's racing here.
default	21:00:55.679662-0700	installd	0x16b0d7000 -[MIInstaller performInstallationWithError:]: Install Successful for (Developer:com.example.testLink); Staging: 0.01s; Waiting: 0.00s; Preflight/Patch: 0.06s, Verifying: 0.65s; Overall: 0.82s
default	21:00:56.007736-0700	runningboardd	com.example.testLink:5:8:3:1:applicationsDidInstall <LSApplicationProxy: 0x1042960e0> com.example.testLink file:///private/var/containers/Bundle/Application/D3FB173A-A2E0-4150-8154-5E04E5A1E588/Runner.app/ <com.example.testLink <installed >:0>
...
default	21:01:03.896668-0700	debugserver	Got a connection, launched process /private/var/containers/Bundle/Application/D3FB173A-A2E0-4150-8154-5E04E5A1E588/Runner.app (pid = 886).
...
default	21:01:04.019418-0700	debugserver	3 +0.000380 sec [036d/1607]: error: ::read ( -1, 0x16f32eb08, 1024 ) => -1 err = Bad file descriptor (0x00000009)
com.apple.runningboard	default	21:01:04.019543-0700	runningboardd	[application<com.example.testLink>:886] Death sentinel fired!

Hello,
I am experiencing this issue too in a separate application.
The application is crashing before Dart debugger can attach to it.
I am pretty new to flutter and working without debugger is causing me to waste a lot of time. XCode debugger is working when stating the application from XCode, but that does not work for Dart.
Similarly, subsequent launches of the app (launching it manually on the tablet) do not crash!
Thank you for any help!
I attached my crash log from the Device logger:

Incident Identifier: 85681A9B-491D-41E1-9AE7-39204CF5179E
CrashReporter Key:   955789e79948ef71afb44be03439184db7c3d819
Hardware Model:      iPad7,11
Process:             Runner [534]
Path:                /private/var/containers/Bundle/Application/F7FBD9F5-7F66-4F45-A9F2-F012B1AACB62/Runner.app/Runner
Identifier:          com.h.hhhhh
Version:             1 (1.0.0)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.h.hhhh [499]
Date/Time:           2020-09-07 18:58:40.5357 +0300
Launch Time:         2020-09-07 18:58:40.3469 +0300
OS Version:          iPhone OS 13.7 (17H35)
Release Type:        User
Baseband Version:    n/a
Report Version:      104
Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Description: DYLD, dependent dylib '@rpath/Flutter.framework/Flutter' not found for '/private/var/containers/Bundle/Application/F7FBD9F5-7F66-4F45-A9F2-F012B1AACB62/Runner.app/Runner'. vm_copy() failure
Highlighted by Thread:  0
Backtrace not available
Unknown thread crashed with ARM Thread State (64-bit):
x0: 0x0000000000000006   x1: 0x0000000000000001   x2: 0x000000016f69d330   x3: 0x0000000000000097
x4: 0x000000016f69cf30   x5: 0x0000000000000000   x6: 0x0000000000000000   x7: 0x0000000000000000
x8: 0x0000000000000020   x9: 0x0000000000000009  x10: 0x6d76202e2772656e  x11: 0x20292879706f635f
x12: 0x6e75522f7070612e  x13: 0x6d76202e2772656e  x14: 0x20292879706f635f  x15: 0x006572756c696166
x16: 0x0000000000000209  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000000
x20: 0x000000016f69cf30  x21: 0x0000000000000097  x22: 0x000000016f69d330  x23: 0x0000000000000001
x24: 0x0000000000000006  x25: 0x000000010101c000  x26: 0x0000000000000001  x27: 0x000000010101c000
x28: 0x0000000000000000   fp: 0x000000016f69cf00   lr: 0x0000000101003ee8
sp: 0x000000016f69cec0   pc: 0x0000000100ffcf68 cpsr: 0x00000000
esr: 0x00000000  Address size fault
Binary images description not available
Error Formulating Crash Report:
Failed to create CSSymbolicatorRef - corpse still valid ¯_(ツ)_/¯
EOF

@cristian1980 It sounds like jenn suspects this may be an ios-deploy bug.  If that is the case you can always launch the app from ios/Runner.xcodeproj / ios/Runner.xcworkspace as a workaround, also this problem wouldn't affect your shipped apps.
I know there was talk recently of updating ios-deploy as part of fixing iOS 14 issues, so you might want to check the latest on the master channel to see if it is addressed.

Running into this one again today as well. The app runs fine via xcode but not from IntelliJ. No amount of cleaning the project etc makes any difference.
Have tried on beta, dev and master with the same result.
At the moment I'm unable to develop on this project as I can't launch from IntelliJ so no hot reloading etc. Can't attach to an app run from xcode since the IntelliJ Flutter plugin can't attach to flavors.

At the moment I'm unable to develop on this project as I can't launch from IntelliJ so no hot reloading etc. Can't attach to an app run from xcode since the IntelliJ Flutter plugin can't attach to flavors.

Jenn will know more of this when she gets back in the office but you can use the command line tools instead of the intellij plugin:

Launch the app from Xcode
flutter attach from the command line
edit the text in intelli j
from the command line press "r" to hot reload

Thanks, yeah that was going to be my approach today. I've narrowed down the issue to a new dependency I added recently. Removing that dependency fixes the problem.

I'm seeing this also, same behaviour on a physical iPad, same log error. I can reproduce it by making a new app from flutter create, and adding either sensors or path_provider as a dependency. So, I'm guessing it might be related to dependencies that use pods.

@jmagman @gaaclarke , I wonder if we shall increase the priority of this issue because I believe

this happens on more apps than just Gallery (I suspect that it happens on almost all Flutter apps)
this happens so frequently (not just 1st run) that I can hardly flutter run or flutter drive any iOS apps locally on iPhone 6s
this happens frequently on our device lab and caused many tests to be flaky

Here are more details from my experience.
It happens very frequently when I test Gallery app or complex_layout app locally with iPhone 6s (but not iPhone 4s). I can keep doing flutter run or flutter drive and it just keeps crashing.
From the command line, it just gets stuck with the following message while the app immediately disappears after launch
Installing and launching...
(This is taking an unexpectedly long time.)       ⣯

With --verbose, we'll see something like
[   +1 ms] executing: /Users/liyuqian/flutter/flutter/bin/cache/artifacts/usbmuxd/iproxy 57484:63131 --udid
2b398993d86f42b05511b330a89ae65289832852
[+1017 ms] Forwarded port ForwardedPort HOST:57484 to DEVICE:63131
[  +66 ms] HttpException: Connection closed before full header was received, uri = http://localhost:57484/ws
[+2013 ms] HttpException: , uri = http://localhost:57484/ws
[+2008 ms] HttpException: , uri = http://localhost:57484/ws
[+2011 ms] HttpException: , uri = http://localhost:57484/ws
[+2010 ms] HttpException: , uri = http://localhost:57484/ws
[+2004 ms] Failed to connect directly, falling back to mDNS

The Failed to connect directly, falling back to mDNS message is observed very frequently in flaky iOS device lab tests (as mentioned in this comment).
Finally, here's a crash log for a complex_layout app flutter run --profile from Xcode
Incident Identifier: 7CE407AB-BEBD-4BB0-AADD-C51EF2A333EC
CrashReporter Key:   e1b06bdbb3a791e46454b77f27ef601c7ac64f57
Hardware Model:      iPhone8,1
Process:             Runner [1089]
Path:                /private/var/containers/Bundle/Application/E7E29C6F-0E1B-44AE-B207-67DDB11D0624/Runner.app/Runner
Identifier:          com.yourcompany.complexLayout
Version:             1 (1.0)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.yourcompany.complexLayout [676]

Date/Time:           2020-09-17 19:38:06.1261 -0700
Launch Time:         2020-09-17 19:38:05.9172 -0700
OS Version:          iPhone OS 13.7 (17H35)
Release Type:        User
Baseband Version:    7.70.01
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Description: DYLD, dependent dylib '@rpath/Flutter.framework/Flutter' not found for '/private/var/containers/Bundle/Application/E7E29C6F-0E1B-44AE-B207-67DDB11D0624/Runner.app/Runner'. vm_copy() failure
Highlighted by Thread:  0

Backtrace not available

Unknown thread crashed with ARM Thread State (64-bit):
    x0: 0x0000000000000006   x1: 0x0000000000000001   x2: 0x000000016fb41350   x3: 0x0000000000000097
    x4: 0x000000016fb40f50   x5: 0x0000000000000000   x6: 0x0000000000000000   x7: 0x0000000000000000
    x8: 0x0000000000000020   x9: 0x0000000000000009  x10: 0x6d76202e2772656e  x11: 0x20292879706f635f
   x12: 0x6e75522f7070612e  x13: 0x6d76202e2772656e  x14: 0x20292879706f635f  x15: 0x006572756c696166
   x16: 0x0000000000000209  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000000
   x20: 0x000000016fb40f50  x21: 0x0000000000000097  x22: 0x000000016fb41350  x23: 0x0000000000000001
   x24: 0x0000000000000006  x25: 0x00000001005dc000  x26: 0x0000000000000001  x27: 0x00000001005dc000
   x28: 0x0000000000000000   fp: 0x000000016fb40f20   lr: 0x00000001005c3ee8
    sp: 0x000000016fb40ee0   pc: 0x00000001005bcf68 cpsr: 0x00000000
   esr: 0x00000000  Address size fault

Binary images description not available

Error Formulating Crash Report:
Failed to create CSSymbolicatorRef - corpse still valid ¯\_(ツ)_/¯

EOF

CC @jonahwilliams @dnfield @xster @godofredoc

@jmagman @gaaclarke How much does this affect the 1.22 beta?

I checked the PRs that appear to have updated ios-deploy which is under suspicion of being the cause of the problem:
aaclarke-macbookpro2:flutter aaclarke$ git log bin/internal/ios-deploy.version
commit 020215bb4c9e8d4fbbc5522f9eeb469fa4727279
Author: Christopher Fujino <christopherfujino@gmail.com>
Date:   Wed Sep 2 18:35:05 2020 -0700

    Update ios-deploy (#65139)

commit 93ca301adca86b49b6acd0102449b7cb509a615e
Author: Christopher Fujino <christopherfujino@gmail.com>
Date:   Wed Jul 22 18:22:59 2020 -0700

    update ios-deploy (#61983)

commit 066cad21a6de8cfdb21e2d780349ac035b420784
Author: Christopher Fujino <christopherfujino@gmail.com>
Date:   Fri Sep 13 11:05:00 2019 -0700

    roll ios-deploy version to 2fbbee77ea2b3212959b9dddda816f59094cd7cd (#40398)

commit 102ab1e6d989de57019e0b1ee003ccb311ca3095
Author: Christopher Fujino <christopherfujino@gmail.com>
Date:   Mon Jul 15 09:22:29 2019 -0700

    Reland bundle ios deps (#36093)

    This updates the flutter tool cache to download binary files for ideviceinstaller, ios-deploy, libimobiledevice, and dynamically linked dependencies from Flutter's GCP bucket.

Those don't seem to match up with the reporting date of May for this bug.

What @SteveAlexander sounds like like the most likely problem.  Cocoapods would be the one responsible for setting up the install_names and copying over the dynamic libraries.

@zanderso I think this has been a source of flakes for a long time (reproduced on 1.12.13) and I see similar reports from 2014 https://forum.ionicframework.com/t/problem-running-ios/9179/4.  I suspect the increased flakiness is due to app size increasing.

@jmagman if this issue isn't the source of the recent increase in flakiness on the dashboard, then I'm fine with dropping the priority on this back down, but the current flakiness is still P0. Is there a different issue we should be tracking that in? Maybe back to the one @jonahwilliams filed this morning?

It's either fix this or reduce the size of the benchmarks (I'm guessing pushed over by e2e).  We can fix this I think.

https://github.com/flutter/flutter/pull/66092 should fix this, holding to see what post submit tests do.

Looks good post-submit, closing.
@liyuqian @josh-burton @SteveAlexander would you mind testing this on the master channel?

@jmagman Sure — result: crash
This is flutter run of a default app with added sensors package dependency, on latest master. I had erased the app on the iPad, so this was the first run on the iPad.
$ flutter run
Running "flutter pub get" in testproject...                         0.3s
Launching lib/main.dart on Stephen’s iPad in debug mode...
Signing iOS app for device deployment using developer identity: "Apple Development: Stephen Alexander (xxx)"
Running pod install...                                              1.2s
Running Xcode build...
 └─Compiling, linking and signing...                        41.7s
Xcode build done.                                           55.8s
Installing and launching...
Failed to attach to the observatory.
Try accepting the local network permissions popup, or enable "Settings > Privacy > Local Network" for your app.
For more information, see https://flutter.dev/docs/development/ios-14#debugging-flutter
Installing and launching...                                       130.9s (!)
Error launching application on Stephen’s iPad.

There was no pop-up. The app launched with a white screen that displayed  "In iOS 14+, Flutter application in debug mode can only be launched from Flutter tooling, IDEs with Flutter plugins or from Xcode. Alternatively, build in profile or release modes to enable re-launching from the home screen."
Additionally, there is no request under "Settings > Privacy > Local Network" on the iPad.
On running a second time, the same thing happens.
From my point of view, this is worse than the situation on master yesterday, as yesterday I could run the app on second launch.

$ flutter doctor -v
[✓] Flutter (Channel master, 1.22.0-10.0.pre.264, on Mac OS X 10.15.6 19G2021 x86_64, locale en-GB)
    • Flutter version 1.22.0-10.0.pre.264 at /Users/steve/code/flutter
    • Framework revision 3e6863ab2b (6 hours ago), 2020-09-18 21:05:27 -0700
    • Engine revision 2abe69c608
    • Dart version 2.10.0 (build 2.10.0-136.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/steve/Library/Android/sdk
    • Platform android-29, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.0, Build version 12A7209
    • CocoaPods version 1.9.3

[✓] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 47.1.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] VS Code (version 1.49.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.14.1

[✓] Connected device (1 available)
    • Stephen’s iPad (mobile) • b0975f3aa3ebe98c71462a866b0356a629fc6aa3 • ios • iOS 14.0
    ! Error: Stephen’s iPad is busy: Copying cache files from device. Xcode will continue when Stephen’s iPad is finished. (code -10)

• No issues found!

@SteveAlexander That looks like a different issue, but very bad and I'd like to track it down.  Between https://github.com/flutter/flutter/issues/65948 and your comment, your iPad upgraded to iOS 14.
Can you file a new issue with and attach the flutter run -v output (it's large, you can attach instead of pasting it)?  Please @ me there.

@jmagman : I tested 3 times locally and all of them pass. Thank you for the fix!

source: gharchive/issue

authors: SteveAlexander cristian1980 gaaclarke jmagman josh-burton liyuqian zanderso

repo: flutter/flutter

license_type: permissive

license_source: github-api


text:
In the isolate, SharedPreferences data cannot be synchronized in real time

cronStock() async {
    _stockCode = _stockCodeController.value.text;
    _growRate = _growRateController.value.text;
    _reduceRate = _reduceRateController.value.text;

    ……

    saveData();
    refreshStock(true);

    await AndroidAlarmManager.periodic(const Duration(seconds: 30), periodicAlarmID, refreshStock, wakeup: true);
}

saveData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.reload();
    try {
        print('0001 saveData: '+DateTime.now().toString());
        prefs.setString('stock_prefix', stockPrefix);
        prefs.setString('stock_code', _stockCodeController.value.text);
        prefs.setDouble('grow_rate', double.parse(_growRateController.value.text));
        prefs.setDouble('reduce_rate', double.parse(_reduceRateController.value.text));
    } on FormatException catch(e) {

    } catch (e) {
        // No specified type, handles all
    }
}

……

refreshStock([bool isManual = false]) {
    print('0002 refreshStock afterTimer: '+DateTime.now().toString());

    Future<List> stockShared = getShared();
    stockShared.then((List shared) {

        print('isManual: $isManual');
        print('shareData: $shared');

    });
}

Future<List> getShared() async {
    print('getShared');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.reload();
    return [
        prefs.getString('stock_prefix'),
        prefs.getString('stock_name'),
        prefs.getString('stock_code'),
        prefs.getDouble('grow_rate'),
        prefs.getDouble('reduce_rate'),

        // 当前值
        prefs.getString('stock_price'),
        prefs.getDouble('stock_rate'),
        prefs.getInt('rate_color'),
    ];
}

Hi @dabpop139
This is currently not possible as far as i know,  shared_preference uses method channel to communicate to native platform and you cannot call it using another isolate
Closing as duplicate of https://github.com/flutter/flutter/issues/13937  If you disagree, please write in the comments and I will reopen it.
Thank you

Hi @dabpop139
This is currently not possible as far as i know, shared_preference uses method channel to communicate to native platform and you cannot call it using another isolate Reference
Closing as duplicate of #13937 If you disagree, please write in the comments and I will reopen it.
Thank you

So what is the workaround?


text:
PageView + PageView + ListView + viewportFraction -> ScrollController attached to multiple scroll views.

Hello,
I've discovered a bug in framework.
Full code (Update 1)
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final PageController _parentPageController = PageController(viewportFraction: 1);
  final PageController _childPageController = PageController();
  final ScrollController _scrollController = ScrollController();

  List<List<FlutterLogo>> _listOfFlutterLogos = [];
  int _currentPage = 0;
  Map<int, int> childSelectionMap = {};

  @override
  void dispose() {
    _parentPageController.dispose();
    _childPageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
        actions: [
          FlatButton(
            child: Text("Add Parent"),
            onPressed: () {
              setState(() {
                _listOfFlutterLogos.add([FlutterLogo()]);
              });
            },
          ),
          FlatButton(
            child: Text("Add Child"),
            onPressed: () {
              setState(() {
                _listOfFlutterLogos[_currentPage].add(FlutterLogo());
              });
            },
          ),
        ],
      ),
      body: PageView.builder(
          controller: _parentPageController,
          itemCount: _listOfFlutterLogos.length,
          onPageChanged: (parentPage) {
            setState(() {
              _currentPage = parentPage;
            });
          },
          itemBuilder: (context, parentIndex) {
            List<FlutterLogo> flutterLogos = _listOfFlutterLogos[parentIndex];
            return Column(
              children: [
                Expanded(
                  child: PageView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      controller: _childPageController,
                      onPageChanged: (childPage) {
                        setState(() {
                          childSelectionMap[_currentPage] = childPage;
                        });
                      },
                      itemCount: flutterLogos.length,
                      itemBuilder: (context, childIndex) {
                        FlutterLogo flutterLogo = flutterLogos[childIndex];
                        return Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Expanded(child: flutterLogo),
                          ],
                        );
                      }),
                ),
                Expanded(
                  child: ListView.builder(
                      controller: _scrollController,
                      scrollDirection: Axis.horizontal,
                      itemCount: flutterLogos.length,
                      itemBuilder: (context, flutterLogoIndex) {
                        return InkWell(
                          onTap: () {
                            setState(() {
                              _childPageController.animateToPage(flutterLogoIndex,
                                  duration: kTabScrollDuration, curve: Curves.easeIn);
                            });
                          },
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                width: 60,
                                height: 60,
                                child: flutterLogos[flutterLogoIndex],
                              ),
                              Container(
                                color: childSelectionMap[_currentPage] == flutterLogoIndex ? Colors.blue : Colors.transparent,
                                height: 10,
                                width: 20,
                              )
                            ],
                          ),
                        );
                      }),
                ),
                Text("Total Parent Lists: ${_listOfFlutterLogos.length}"),
                Text("Current Page: $_currentPage"),
              ],
            );
          }),
    );
  }
}

Reproduction steps:

Run app;
Click on Add Parent 3 times (until you see Total Parent Lists: 3);
Scroll to next page (Current Page: 1);
Click on Add Child 3 times;
Click on any of the child widgets on the bottom.

ScrollController attached to multiple scroll views.
'package:flutter/src/widgets/scroll_controller.dart':
Failed assertion: line 113 pos 12: '_positions.length == 1'

Without viewportFraction it works well.
Looking forward for any advice in this case.

Hi @zeromaro,
I tried your code and it does throw the exception upon tapping on child widgets, but the error says ScrollController attached to multiple scroll views.
Can you try to make ScrollController variable and add it as a controller and see if it works ?

Hello @darshankawar ,
I've added scroll controller - behaviour didn't change. With viewportFraction less than 1 it will still crash.

Issue is replicable on latest Stable (1.20.1).

Can not repro on up-to-date master-branch,
PS F:\flutter_dev\src_new\flutter> flutter doctor -v
[√] Flutter (Channel master, 1.21.0-8.0.pre.172, on Microsoft Windows [Version 10.0.17763.615], locale en-US)
    • Flutter version 1.21.0-8.0.pre.172 at F:\flutter_dev\src_new\flutter
    • Framework revision 8dcb4c338a (2 hours ago), 2020-08-11 17:29:35 -0700
    • Engine revision 06458d2f6c
    • Dart version 2.10.0 (build 2.10.0-11.0.dev)
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at C:\Users\Administrator\AppData\Local\Android\sdk
    • Platform android-29, build-tools 29.0.3
    • Java binary at: C:\Program Files\Android\Android Studio1\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
    • All Android licenses accepted.

[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.7.0)
    • Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
    • Visual Studio Community 2019 version 16.7.30330.147
    • Windows 10 SDK version 10.0.18362.0

[√] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio1
    • Flutter plugin version 48.1.1
    • Dart plugin version 192.8052
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[√] VS Code (version 1.47.2)
    • VS Code at C:\Users\Administrator\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.12.1

[√] Connected device (2 available)
    • PDCM00 (mobile)   • 9LL7VO8XUOIN75ZH • android-arm64 • Android 10 (API 29)
    • Windows (desktop) • windows          • windows-x64   • Microsoft Windows [Version 10.0.17763.615]

• No issues found!

I am having the same issue.

I have a vertical PageView, inside each page there's a vertical CustomScrollView (scrolling has been implemented manually through RawGestureDetector).
I have to manage a List of ScrollControllers, since each CustomScrollView needs a controller through which I'm handling vertical swipes (I have to manage if the screen gets scrolled or the page gets changed).
import 'package:floating_bottom_navigation_bar/floating_bottom_navigation_bar.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:tethered/screens/components/gap.dart';
import 'package:tethered/screens/home/book_details_page/components/book_details_info_text.dart';
import 'package:tethered/theme/size_config.dart';
import 'package:tethered/utils/colors.dart';
import 'package:tethered/utils/text_styles.dart';
import 'package:zefyr/zefyr.dart';

class ReadingPage extends StatefulWidget {
  @override
  _ReadingPageState createState() => _ReadingPageState();
}

class _ReadingPageState extends State<ReadingPage> {
  PageController _pageController;
  List<ScrollController> _listScrollControllers;
  ScrollController _activeScrollController;
  Drag _drag;
  ValueNotifier<bool> _isVisible = ValueNotifier(true);

  Null Function() Function(ScrollController) _changeBarVisibility;

  int numberOfPages = 15;
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: 0,
      viewportFraction: 1,
      keepPage: true,
    );
    if (numberOfPages <= 3) {
      _listScrollControllers = List.filled(
        numberOfPages,
        ScrollController(),
        growable: true,
      );
    } else {
      _listScrollControllers = List.filled(
        3,
        ScrollController(),
        growable: true,
      );
    }

    _listScrollControllers.forEach((controller) {
      if (_changeBarVisibility == null) {
        _changeBarVisibility = (ScrollController scrollController) => () {
              // ignore: invalid_use_of_protected_member
              scrollController.positions.forEach((position) {
                if (position.userScrollDirection == ScrollDirection.reverse) {
                  _isVisible.value = false;
                }
                // ignore: invalid_use_of_protected_member
                if (position.userScrollDirection == ScrollDirection.forward) {
                  _isVisible.value = true;
                }
              });
            };
      }
      controller.addListener(_changeBarVisibility(controller));
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    _listScrollControllers.forEach((controller) {
      controller.removeListener(_changeBarVisibility(controller));
      controller.dispose();
    });
    super.dispose();
  }

  void _handleDragStart(DragStartDetails details) {
    if (_listScrollControllers[currentIndex].hasClients &&
        _listScrollControllers[currentIndex].position.context.storageContext !=
            null) {
      final RenderBox renderBox = _listScrollControllers[currentIndex]
          .position
          .context
          .storageContext
          .findRenderObject();
      if (renderBox.paintBounds
          .shift(renderBox.localToGlobal(Offset.zero))
          .contains(details.globalPosition)) {
        _activeScrollController = _listScrollControllers[currentIndex];
        _drag = _activeScrollController.position.drag(details, _disposeDrag);
        return;
      }
    }
    _activeScrollController = _pageController;
    _drag = _pageController.position.drag(details, _disposeDrag);
  }

  void _handleDragUpdate(DragUpdateDetails details) {
    var scrollDirection = _activeScrollController.position.userScrollDirection;

    if (_activeScrollController == _listScrollControllers[currentIndex] &&
        ((scrollDirection == ScrollDirection.reverse) &&
                _activeScrollController.offset.roundToDouble() >=
                    _activeScrollController.position.maxScrollExtent
                        .roundToDouble() ||
            (scrollDirection == ScrollDirection.forward) &&
                _activeScrollController.offset < 0)) {
      _activeScrollController = _pageController;
      _drag?.cancel();
      _drag = _pageController.position.drag(
        DragStartDetails(
          globalPosition: details.globalPosition,
          localPosition: details.localPosition,
        ),
        _disposeDrag,
      );
    }
    _drag?.update(details);
  }

  void _handleDragEnd(DragEndDetails details) {
    _drag?.end(details);
  }

  void _handleDragCancel() {
    _drag?.cancel();
  }

  void _disposeDrag() {
    _drag = null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: ValueListenableBuilder<bool>(
          valueListenable: _isVisible,
          builder: (context, isVisible, _) {
            return AnimatedContainer(
              color: TetheredColors.primaryDark,
              duration: Duration(milliseconds: 200),
              height: isVisible ? sx * 10 : 0.0,
              child: AnimatedContainer(
                duration: Duration(milliseconds: 200),
                height: isVisible ? sx * 10 : 0.0,
                width: sy * 90,
                child: Wrap(
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: FloatingNavbar(
                        unselectedItemColor: Colors.white,
                        selectedItemColor: Colors.white,
                        selectedBackgroundColor: Colors.transparent,
                        backgroundColor: Colors.transparent,
                        onTap: (int val) {
                          //returns tab id which is user tapped
                          _pageController.nextPage(
                              duration: Duration(milliseconds: 500),
                              curve: Curves.easeOutSine);
                        },
                        currentIndex: 0,
                        items: [
                          FloatingNavbarItem(icon: Icons.home, title: 'Home'),
                          FloatingNavbarItem(
                              icon: Icons.explore, title: 'Explore'),
                          FloatingNavbarItem(
                              icon: Icons.chat_bubble_outline, title: 'Chats'),
                          FloatingNavbarItem(
                              icon: Icons.settings, title: 'Settings'),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            );
          }),
      // extendBody: true,

      // bottomNavigationBar: Container(),
      // backgroundColor: TetheredColors.primaryDark,
      body: ZefyrTheme(
        data: ZefyrThemeData(
          attributeTheme: AttributeTheme(
            bold: TextStyle(
              color: Colors.deepOrange,
            ),
            heading1: LineTheme(
              textStyle: TextStyle(color: Colors.blue),
              padding: EdgeInsets.zero,
            ),
          ),
        ),
        child: RawGestureDetector(
          gestures: <Type, GestureRecognizerFactory>{
            VerticalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<
                    VerticalDragGestureRecognizer>(
                () => VerticalDragGestureRecognizer(),
                (VerticalDragGestureRecognizer instance) {
              instance
                ..onStart = _handleDragStart
                ..onUpdate = _handleDragUpdate
                ..onEnd = _handleDragEnd
                ..onCancel = _handleDragCancel;
            })
          },
          behavior: HitTestBehavior.opaque,
          child: PageView.builder(
              physics: NeverScrollableScrollPhysics(),
              dragStartBehavior: DragStartBehavior.down,
              controller: _pageController,
              scrollDirection: Axis.vertical,
              itemCount: numberOfPages,
              onPageChanged: (index) {
                setState(() {
                  // if (currentIndex > index) {
                  //   final newController = ScrollController();
                  //   // newController.addListener(_changeBarVisibility);
                  //   _listScrollControllers[index] = newController;
                  // }

                  if (_listScrollControllers.length < numberOfPages &&
                      currentIndex < index) {
                    final newController = ScrollController();
                    newController
                        .addListener(_changeBarVisibility(newController));
                    _listScrollControllers.add(newController);
                  }
                  currentIndex = index;
                  // _activeScrollController = _listScrollControllers[index];
                });
              },
              itemBuilder: (context, index) => CustomScrollView(
                    physics: NeverScrollableScrollPhysics(),
                    controller: _listScrollControllers[index],
                    slivers: [
                      SliverAppBar(
                        actions: [],
                        backgroundColor: TetheredColors.primaryDark,
                        floating: true,
                      ),
                      SliverToBoxAdapter(
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: sy * 4),
                          child: Column(
                            children: [
                              Gap(height: 5),
                              Text(
                                'The Story of How London Got Its Name',
                                textAlign: TextAlign.center,
                                style:
                                    TetheredTextStyles.authSubHeading.copyWith(
                                  color: TetheredColors.readingPageTitle,
                                ),
                              ),
                              Gap(height: 5),
                              Wrap(
                                alignment: WrapAlignment.center,
                                children: [
                                  BookDetailsInfoText(
                                    icon: Icons.visibility,
                                    text: '21M views',
                                    color: TetheredColors.readingPageInfo,
                                  ),
                                  BookDetailsInfoText(
                                    icon: Icons.arrow_upward,
                                    text: '12K upvotes',
                                    color: TetheredColors.readingPageInfo,
                                  ),
                                  BookDetailsInfoText(
                                    icon: Icons.list,
                                    text: '21 Tethers',
                                    color: TetheredColors.readingPageInfo,
                                  ),
                                ],
                              ),
                              Gap(height: 5),
                              ZefyrView(
                                document: NotusDocument.fromJson(content),
                              ),
                              Gap(height: 5),
                            ],
                          ),
                        ),
                      ),
                    ],
                  )),
        ),
      ),
    );
  }

This is the code for the screen. It's a big project, so there's a lot of unrelated stuff.
I am getting this ScrollController attached to multiple scroll views issue too. I would appreciate it if someone can help
These are the dependencies:
dependencies:
  flutter:
    sdk: flutter
  get: ^3.10.2
  injectable: ^1.0.4
  firebase_core: ^0.5.0
  firebase_analytics: ^6.0.0
  firebase_auth: ^0.18.0+1
  cloud_firestore: ^0.14.0+2
  get_it: ^4.0.2
  carousel_slider: ^2.2.1
  badges: ^1.1.1
  cached_network_image: ^2.3.2+1
  shimmer: ^1.1.1
  pull_to_refresh: ^1.6.1
  flutter_spinkit: "^4.1.2"

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.3
  google_fonts: ^1.1.0
  flutter_bloc: ^6.0.1
  provider: ^4.3.2+2
  zefyr:
    git:
      url: https://github.com/memspace/zefyr.git
      path: packages/zefyr
  notus: ^0.1.5
  floating_bottom_navigation_bar: ^1.4.1
  flutter_snake_navigationbar: ^0.4.0+1

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: null
  injectable_generator: ^1.0.4

I was able to solve the issue after some refactor and after I've extracted widgets to StatefulWidget classes. However I still think it's some kind of bug.

I have the same issue here, so confusing with this bug

Hello , i've the same issue here and thats my code
SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Column(
children: [
Container(
width: 344,
height: 235,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.circular(25.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: PageView.builder(
itemCount: myPosts[i].images.length,
scrollDirection: Axis.horizontal,
controller: _pageController,
itemBuilder: (c, ind) => CachedNetworkImage(
errorWidget: (context, url, error) => Icon(Icons.error),
placeholder: (context, url) => FittedBox(
fit: BoxFit.none,
child: Container(
width: 80,
height: 80,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.blueGrey),
),
),
),
imageUrl: myPosts[i].images[ind],
fit: BoxFit.fill,
),
),
),
),
myPosts[i].images.length == 1
? Offstage()
: Padding(
padding: EdgeInsets.only(top: 10),
child: SmoothPageIndicator(
controller: _pageController,
count: myPosts[i].images.length,
effect: WormEffect(),
),
),
],
),
),
         I using   smooth_page_indicator: ^0.2.3

This comment may be of some help from similar issue: https://github.com/flutter/flutter/issues/63458#issuecomment-718348235
You cannot access the position of a ScrollController and manipulate it if there is more than one attached. You can check first if there is more than one position, or access the one you want directly using the getter ScrollController.positions.
I am going to close this as I think it is working as intended, but if not, please update and we will take another look! Thanks!

authors: AcnoSaga Jojoooo1 OmarBakry-eg Piinks darshankawar deimantasa sangle1996 xu-baolin zeromaro


text:
CanvasKit uses too much memory (~100KB) per laid out paragraph

The problem is present only when: --dart-define=FLUTTER_WEB_USE_SKIA=true
Works fine in regular web mode.

mem_leak_skia.zip
Flutter beta channel 1.22.0-12.1.pre
Windows 10 2004
Chrome 85.0.4183.102 64bit
Logs
flutter doctor -v
[√] Flutter (Channel beta, 1.22.0-12.1.pre, on Microsoft Windows [Version 10.0.19041.508], locale en-US)
    • Flutter version 1.22.0-12.1.pre at c:\Programs\flutter
    • Framework revision 8b3760638a (9 days ago), 2020-09-15 17:47:13 -0700
    • Engine revision 4654fc6cf6
    • Dart version 2.10.0 (build 2.10.0-110.3.beta)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at C:\Users\slavap\AppData\Local\Android\sdk
    • Platform android-29, build-tools 29.0.2
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • CHROME_EXECUTABLE = c:\Programs\chrome-debug.bat

[!] Android Studio (version 3.6)
    • Android Studio at C:\Program Files\Android\Android Studio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)

[√] VS Code, 64-bit edition (version 1.49.2)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 3.14.1

[√] Connected device (3 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 10 (API 29) (emulator)
    • Web Server (web)                   • web-server    • web-javascript • Flutter Tools
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 85.0.4183.102

! Doctor found issues in 1 category.

Hi @slavap
I tried your code sample on latest beta on Mac, but didn't see the memory spiking.

I kept running the app for 2 minutes. Is there a specific pattern to see the memory leak ?
Thanks.

@darshankawar have you run it with — dart-define=FLUTTER_WEB_USE_SKIA=true ?
Also I’m getting this leak on Windows, not on Mac

Since I don't have windows to replicate the issue, I am keeping this issue open for further analysis and additional triage.

May be related to 56938

/cc @hterkelsen

I've ran the sample for about an hour. WASM memory size grew to 481MB quickly, then continued glacially growing to 577MB. So I think if there is a leak, it should be a fairly small one. However, Chrome's Task Manager kept growing faster, starting at 600MB and growing to 1.1GB within the same time period. Something tells me it's more than CanvasKit memory leak. We'll need to investigate further.

Raising the priority again. After looking into this more I found that one laid out single-character paragraph costs 100KB. All this app does it stamp out thousands of single-character paragraphs, making the issue very noticeable. This is not a leak, but it is a pretty bad inefficiency.

Corresponding Skia issue: https://bugs.chromium.org/p/skia/issues/detail?id=11028

@slavap While we're investigating the issue on the Skia side, I have a workaround for your app. I noticed that the app renders one character per paragraph, and the characters are repeated a lot. There are only 97 unique characters. So as an optimization I cached each character as a Picture and reused that picture throughout the frame. That keeps CanvasKit memory usage consistently under 30MB (although it allocates a 128MB buffer for future growth).
Here's the modified version of the app:
import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: MyEffect(),
    );
  }
}

class MyEffect extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyEffectState();
}

class _MyEffectState extends State<MyEffect> {
  final List<Widget> _verticalLines = [];
  Timer _timer;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance
        .addPostFrameCallback((timeStamp) => _startTimer());
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: _verticalLines);
  }

  void _startTimer() {
    _timer =
        Timer.periodic(Duration(milliseconds: 300), (timer) => _addVertLine());
  }

  void _addVertLine() {
    var line = _getVerticalTextLine(context);
    setState(() => _verticalLines.add(line));
  }

  Widget _getVerticalTextLine(BuildContext context) {
    final Key key = UniqueKey();
    return Positioned(
      key: key,
      left: Random().nextDouble() * MediaQuery.of(context).size.width,
      child: VerticalTextLine(
        onFinished: () {
          final w = _verticalLines.firstWhere((element) => element.key == key);
          setState(() => _verticalLines.remove(w));
        },
      ),
    );
  }
}

class VerticalTextLine extends StatefulWidget {
  const VerticalTextLine({@required this.onFinished, Key key})
      : super(key: key);

  final VoidCallback onFinished;

  @override
  _VerticalTextLineState createState() => _VerticalTextLineState();
}

@immutable
class CharacterPicture {
  CharacterPicture(this.character, this.width, this.height, this.picture);

  final String character;
  final double width;
  final double height;
  final ui.Picture picture;
}

class _VerticalTextLineState extends State<VerticalTextLine> {
  List<Widget> _characters = <Widget>[];
  Timer _timer;

  static Map<String, CharacterPicture> _characterPictures = <String, CharacterPicture>{};

  CharacterPicture _render(String character) {
    return _characterPictures.putIfAbsent(character, () {
      final ThemeData theme = Theme.of(context);
      final ui.ParagraphBuilder b = ui.ParagraphBuilder(ui.ParagraphStyle(
        fontFamily: theme.textTheme.bodyText1.fontFamily,
        fontSize: theme.textTheme.bodyText1.fontSize,
        textDirection: Directionality.of(context),
      ));
      b.pushStyle(ui.TextStyle(
        color: Colors.amberAccent,
      ));
      b.addText(character);
      b.pop();
      final ui.Paragraph p = b.build();
      p.layout(const ui.ParagraphConstraints(width: 1000));
      final ui.PictureRecorder recorder = ui.PictureRecorder();
      final ui.Canvas canvas = ui.Canvas(recorder);
      canvas.drawParagraph(p, ui.Offset.zero);
      final ui.Picture picture = recorder.endRecording();
      return CharacterPicture(
        character,
        p.width,
        p.height,
        picture,
      );
    });
  }

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      if (_characters.length >= 100) {
        _timer.cancel();
        widget.onFinished();
        return;
      }

      final int charCode = 32 + Random().nextInt(96);
      String ch = String.fromCharCode(charCode);
      final CharacterPicture picture = _render(ch);

      setState(() {
        _characters.add(Container(
          key: ValueKey<int>(10000 * charCode + _characters.length),
          width: picture.width,
          height: picture.height,
          child: CustomPaint(
            painter: CharacterPainter(picture),
          ),
        ));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: _characters);
  }
}

class CharacterPainter extends CustomPainter {
  CharacterPainter(this.characterPicture);

  final CharacterPicture characterPicture;

  @override
  void paint(ui.Canvas canvas, ui.Size size) {
    canvas.drawPicture(characterPicture.picture);
  }

  @override
  bool shouldRepaint(covariant CharacterPainter oldDelegate) {
    return oldDelegate.characterPicture.character != characterPicture.character;
  }
}

@yjbanov Thank you! I will try this approach.

After testing some typical apps I see that the GC is able to stay on top of outstanding paragraph collection. I haven't seen more than 500 outstanding paragraphs at any given point in time. Given that the use-case in this issue report has a workaround and that typical apps are not affected as much, I'm reducing priority back to P4.

I can reproduce issue 1.26 and even on 1.25 using canvaskit
Canvaskit

HTML

code sample
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  final fontsList = <String>[];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Test')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 'fonts' or 'localFonts'
            for (final it in List.generate(12, (_) => 0))
              fontsList.addAll(fonts.split('\n'));

            Navigator.of(context).push(MaterialPageRoute(
              builder: (_) => FontsPage(fontsList: fontsList),
            ));
          },
          child: Text('Next Page'),
        ),
      ),
    );
  }
}

class FontsPage extends StatelessWidget {
  const FontsPage({
    Key key,
    @required this.fontsList,
  }) : super(key: key);

  final List<String> fontsList;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Scrollbar(
        child: ListView.separated(
          itemCount: fontsList.length,
          separatorBuilder: (_, __) => Divider(height: 40.0),
          itemBuilder: (_, index) {
            final isEven = index % 2 == 0;
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                isEven ? 'přížíéščé č' : '订单, asdf',
                // if using 'localFonts' uncomment this:
                // style: TextStyle(
                //   fontFamily: fontsList[index],
                //   fontSize: 58.0,
                // ),
                style: GoogleFonts.getFont(fontsList[index]).copyWith(
                  fontSize: 58,
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

// Google Fonts
const fonts = """
Ubuntu
Titillium Web
Stalinist One
Source Sans Pro
Source Code Pro
Roboto Condensed
Roboto
PT Serif
PT Sans Narrow
PT Sans
Poppins
Oxygen
Open Sans
Nunito Sans
Nunito
Noto Serif
Noto Sans
Nanum Gothic
Mukta
Montserrat
Merriweather
Lobster
Libre Baskerville
Lexend Mega
Lexend Giga
Lato
Jomhuria
IBM Plex Sans
Hind Siliguri
Hanalei
Hammersmith One
Fjalla One
Fira Sans
Crimson Text
Big Shoulders Display
Bebas Neue
Barlow
Anton
Abel""";

// load fonts from assets without GoogleFonts lib
const localFonts = """
Ubuntu
TitilliumWeb
StalinistOne
SourceSansPro
SourceCodePro
Slabo27px
RobotoCondensed
Roboto
PTSerif
PTSansNarrow
PTSans
Poppins
Oxygen
OpenSans
NunitoSans
Nunito
NotoSerif
NotoSans
NanumGothic
Mukta
Montserrat
Merriweather
Lobster
LibreBaskerville
LexendMega
LexendGiga
Lato
Jomhuria
IBMPlexSans
HindSiliguri
Hanalei
HammersmithOne
FjallaOne
FiraSans
CrimsonText
BigShouldersDisplay
Benne
BebasNeue
Barlow
Anton
Abel
""";

flutter doctor -v
[✓] Flutter (Channel beta, 1.25.0-8.3.pre, on Microsoft Windows [Version 10.0.19042.804], locale en-US)
    • Flutter version 1.25.0-8.3.pre at C:\Users\Taha\Code\flutter
    • Framework revision 5d36f2e7f5 (5 weeks ago), 2021-01-14 15:57:49 -0800
    • Engine revision 7a8f8ca02c
    • Dart version 2.12.0 (build 2.12.0-133.7.beta)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\Taha\Code\SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = C:\Users\Taha\Code\SDK
    • Java binary at: C:\Users\Taha\Code\android-studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.
[✓] Chrome - develop for the web
    • Chrome at C:\Users\Taha\AppData\Local\Google\Chrome\Application\chrome.exe
[✓] Android Studio (version 4.1.0)
    • Android Studio at C:\Users\Taha\Code\android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[✓] VS Code (version 1.53.2)
    • VS Code at C:\Users\Taha\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.19.0
[✓] Connected device (2 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150
    • Edge (web)   • edge   • web-javascript • Microsoft Edge 84.0.522.52
• No issues found!

[✓] Flutter (Channel beta, 1.26.0-17.5.pre, on Microsoft Windows [Version 10.0.19042.804], locale en-US)
    • Flutter version 1.26.0-17.5.pre at C:\Users\Taha\Code\flutter_beta
    • Framework revision 1fe38dcb5f (5 days ago), 2021-02-10 16:25:47 -0800
    • Engine revision d4453f6018
    • Dart version 2.12.0 (build 2.12.0-259.9.beta)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\Taha\Code\SDK
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = C:\Users\Taha\Code\SDK
    • Java binary at: C:\Users\Taha\Code\android-studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.
[✓] Chrome - develop for the web
    • Chrome at C:\Users\Taha\AppData\Local\Google\Chrome\Application\chrome.exe
[✓] Android Studio (version 4.1.0)
    • Android Studio at C:\Users\Taha\Code\android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
[✓] VS Code (version 1.53.2)
    • VS Code at C:\Users\Taha\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension version 3.19.0
[✓] Connected device (2 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150
    • Edge (web)   • edge   • web-javascript • Microsoft Edge 84.0.522.52
• No issues found!

This seems to affect our app as well - we draw a lot of CustomPaint-based markers and the memory usage just grows over time, the more of them we show (even if we navigate elsewhere, they seem to not be garbage collected).

I have the same issue
there is the minimal sample
when I run it in web, and change tab for many times, the memory will get too high
Enviroment
[✓] Flutter (Channel stable, 2.0.5, on Mac OS X 10.15.7 19H2 darwin-x64, locale zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] Connected device (2 available)
sample
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '动态组件',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TestPage(),
    );
  }
}

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

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> with TickerProviderStateMixin {
  TabController _tabController;

  final _curIndex = ValueNotifier(0);

  int get curIndex => _curIndex.value;

  @override
  void initState() {
    _tabController = TabController(length: tabs.length, vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: buildBody(),
    );
  }

  Widget buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          buildTabs(),
          SizedBox(height: 20),
          buildViews(),
        ],
      ),
    );
  }

  Widget buildTabs() {
    return TabBar(
      indicatorSize: TabBarIndicatorSize.label,
      onTap: (index) {
        if (curIndex == index) return;
        _curIndex.value = index;
      },
      tabs: List.generate(
        tabs.length,
        (index) {
          final cur = tabs[index];
          return Column(
            children: [
              Text(cur, style: TextStyle(color: Colors.black),),
              SizedBox(height: 4),
            ],
          );
        },
      ),
      controller: _tabController,
      isScrollable: true,
    );
  }

  Widget buildViews() {
    return Expanded(
      child: ValueListenableBuilder(
          valueListenable: _curIndex,
          builder: (context, value, _) {
            final curTab = tabs[value];
            final curList = dataList[curTab];
            final length = curList.length;
            return ListView.builder(
              padding: EdgeInsets.only(top: 26),
              itemBuilder: (ctx, index) {
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: List.generate(_crossCount, (i) {
                    final isFirstInLine = i == 0;
                    final curIndex = index * _crossCount + i;
                    final cur = curList[curIndex];
                    return Padding(
                      padding: EdgeInsets.only(left: isFirstInLine ? 0 : 66),
                      child: Container(
                        width: 210,
                        padding: EdgeInsets.only(bottom: 30),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              width: 210,
                              height: 127,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(6),
                                color: randomColor,
                              ),
                              child: Center(
                                child: Icon(
                                  Icons.image,
                                  color: Colors.white,
                                  size: 50,
                                ),
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 20, bottom: 10),
                              child: Text(
                                cur.one,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: color1,
                                  height: 1,
                                ),
                                maxLines: 1,
                              ),
                            ),
                            Text(
                              cur.two,
                              style: TextStyle(
                                fontSize: 18,
                                color: Colors.black,
                                height: 1.25,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 3,
                              overflow: TextOverflow.clip,
                            ),
                            SizedBox(height: 10),
                            Text(
                              cur.three,
                              style: TextStyle(
                                fontSize: 14,
                                color: color2,
                                height: 1.25,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 3,
                              overflow: TextOverflow.clip,
                            ),
                          ],
                        ),
                      ),
                    );
                  }),
                );
              },
              itemCount: (length / _crossCount).ceil(),
            );
          }),
    );
  }
}

const color1 = Color(0xff8C8D92);
const color2 = Color(0xff656B76);

const int _crossCount = 4;

const int _length = 16;

final List<String> tabs = List.generate(3, (index) => 'TAB-$index');

final Map<String, List<_Data>> dataList = {
  tabs[0]: buildDataList,
  tabs[1]: buildDataList,
  tabs[2]: buildDataList,
};

class _Data {
  _Data(this.one, this.two, this.three);

  final String one;
  final String two;
  final String three;
}

List<_Data> get buildDataList => List.generate(
    _length,
    (index) => _Data(
          buildRandomText(length: 30 + Random().nextInt(15)),
          buildRandomText(length: 20 + Random().nextInt(10)),
          buildRandomText(length: 10 + Random().nextInt(5)),
        ));

String buildRandomText({int length = 30}) {
  String input = '卡拉斯贷记卡结束打卡结束的考拉绝世独立卡觉得少了卡就是打开链接啊点开链接啊但是看了俺们说不定'
      '明年必须支持美女把监控设备的俺说的话意思idioms低哦啊u山东u奥速度哦啊苏丹阿斯度过阿精美鼠标垫就啊不能说的';
  int length = 30;

  /// 生成的字符串固定长度
  String result = '';
  for (var i = 0; i < length; i++) {
    result = result + input[Random().nextInt(input.length)];
  }
  return result;
}

Color get randomColor =>
    Colors.accents[Random().nextInt(Colors.accents.length)];

Update: I'm going to fix the memory issue caused by sample apps provided in this issue via https://github.com/flutter/engine/pull/26438. However, performance will still degrade if thousands of unique paragraphs need to rendered all at once. Ultimately laying out thousands of paragraphs will always be expensive, but we can (and should) optimize it as well as we can. For example, https://github.com/flutter/flutter/issues/81224 will allows us to transfer render data for paragraphs cheaply between layout and rendering, which should improve performance by a constant factor. We have other data transfer inefficiencies that we can look into later.

authors: TahaTesser asjqkkkk darshankawar ferhatb kubaprzetakiewicz slavap yjbanov


text:
Gray square in place of widget - only if app is instaled from Google Play Store

Problem Description:
Gray square in place of widget - only if app is instaled from Google Play Store #67868
Problem cause:
After removing in Text child widget textAlign: TextAlign.justify, works fine.
In this case Text Widget is a problem.

Hi @lukaszSieczkowski
Looks like you have filed this issue  already
Closing as duplicate of https://github.com/flutter/flutter/issues/67868

Yes but is closed without understanding a problem

authors: TahaTesser lukaszSieczkowski


text:
Make tests compile and run faster

Use case
According to flutter.dev one of the things flutter aims at is fast development. I think being able to develop in a TDD workflow contributes to this goal.
In our case, we have suite about 500 tests, consisting of unit and widget tests. In order to facilitate a real TDD workflow, all the tests should run very fast. There are some sources that suggest a maximum executing time of less than 10s: https://blog.ploeh.dk/2012/05/24/TDDtestsuitesshouldrunin10secondsorless/#:~:text=The test suite you work,be faster than 10 milliseconds.
Currently, our test suite is executing in about 2min, which makes the TDD approach very hard, because it disrupts your workflow (better described in the article).
Proposal
The aim of this ticket is more to collect all the tickets, that would contribute to a better TDD experience. So please add additional things that prevent you from a good TDD experience.
Live Unit Testing
https://github.com/flutter/flutter/issues/4719
https://github.com/Dart-Code/Dart-Code/issues/2878
Improve Performance of Tests
https://github.com/flutter/flutter/issues/17130
https://github.com/dart-lang/sdk/issues/32953
Hot Reload for Unit Tests
https://github.com/flutter/flutter/issues/25973
https://github.com/szotp/hottie/
Please consider 👍 this and linked tickets if you thing this is important.

Hi @HerrNiklasRaab
I looked at the link you posted an I got this piece:

That test suite doesn't need to be the same as is running on your CI server. It could be a subset of tests. That's OK. The TDD suite may just be part of your Test Pyramid.

I'm wondering if you are running all the tests of the project or just a subset of tests related to the [new] test you are adding?
I personally think that the duration of tests will always depend on the numbers of tests you are running and we can't just make 10.000+ tests to run in 10 seconds. As your tests increase the time will increase as well.

Hey @pedromassangocode,
thanks for your response. Sure if the project grows very much, at some point you will need to split it into multiple test suits. But currently, we have 500 tests, who take about 2min. This I think is definitely too long.

I'm wondering if you are running all the tests of the project or just a subset of tests related to the [new] test you are adding?

Currently, we are running the tests of the whole project.
Maybe we can keep this ticket open to track the experience from the point of view of a TDD developer.
Best regards,
Niklas

Cc @Hixie @HansMuller

@HerrNiklasRaab We will need more information to help here, for example, some profiles and traces of running the tests in question to see where the time is going.
It would also be good to have an estimate of how long each test should take. Is it reasonable for a test to take 250ms on average? Or should it be faster? Also, it would be useful to know whether you get different performance by changing the -j option to change how many cores are being used.

Hi @Hixie,
Thanks for your answer.
I think the most important part of unit tests is that they run fast, with fast I mean very fast. As soon as they are so slow that you don't run them every few minutes they turn into a burden. With fast tests your workflow looks like:
With fast tests:

Run all tests
Change one thing
Run all tests → When it fails you know exactly what which change caused the failure

With slow tests

Run all tests
You change multiple things because tests are slow
You end up with multiple test failing, you need to start debugging, find the changes that caused the failure

My argument is, that the faster the tests run, the shorter this loop is, the more efficient you are developing, because your mind only needs to concentrate on one thing. You never need to debug.
Having very fast tests is crucial. That's why I think 250ms is way too long (no offense). I worked on projects with 5ms per test. This means you can have 2000 tests in your suite and they are still running in 10s.
With 250ms you can only execute 40 tests in 10s. This means you either run them not as often, (consequences described above) or you need to spend a lot of time thinking which test to run. This is very difficult (because you don't know which tests are affected by your change), time-consuming and there is no support in the IDE for running only a subset of tests.

I tried it with "-j", and it yielded a slight improvement. I have also the logs when running with "-v" but I am not sure if this is what you meant with "some profiles and traces of running the tests".
Verbose logs: text-verbose.txt.zip

Thanks very much and very interested in your response,
Niklas
PS: If improving the testspeed by this ammount is not possible due to technical reasons. Maybe it might be worth having a look at this project, which yields the hot reload: https://github.com/szotp/hottie/

By profiles I mean instrumenting the code as it runs to see what is being slow (https://en.wikipedia.org/wiki/Profiling_(computer_programming)). The Dart debugger supports profiling. It should be possible to profile a test run from the flutter tool by starting it in the debugger, then attaching to the debugger, enabling the profiler, resuming the code, and seeing what it lists. Similarly the timeline traces can be obtained from the debugger. They show how much time was spent doing various things. We may need to instrument the tests to measure time spent preparing the tests vs executing them, etc.
5ms per test seems reasonable as a target. On my 20-core machine, running the flutter unit tests, I get about 20ms per test. It could definitely be faster.
One thing you can do to make things faster is toggle debugCheckIntrinsicSizes. Specifically, create a test binding (AutomoatedTestWidgetsFlutterBinding subclass) that returns false for "checkIntrinsicSizes", and instantiate that before calling testWidgets the first time. That might help a lot. (Doing this disables an expensive test that checks for intrinsic contract violations. If you're making your own RenderBox subclasses you want it enabled but otherwise you could just turn it off if you have a lot of tests without losing much value.)

Hello,
thank you very much for your suggestion (toggle debugCheckIntrinsicSizes). It reduced the time of the 359 tests from 1:00 to 0:50, about 10-12s which is nice :)
Here are stats in order get a feeling of the difference in computation speed between your and my machine:
20ms / test for tests of flutter on your machine
62ms / test for tests of flutter on my machine (Quad Core)
136ms / test for fazua_toolbox_app on my machine (Quad Core)
Also quite interesting is, that the average time per test on our project (fazua_toolbox_app) is 136ms / test and when I run the tests from flutter on my machine it executes much faster, with 136ms / test. To me, this either means that our tests (or widgets in our tests) are more complex, or there are things we can improve without changes in the "flutter test" tool.
My profiling attempt
I am sure I didn't execute to steps regarding profiling, like you described, because I didn't understand them fully. Nevertheless, I tried my best. So this is what I did:

I picked a test file, with a few widget test, that have remarkably slow executing speed of 347ms / test.
I added debugger() at the end of the last tests.
I run the test with the following command flutter test --start-paused "test/widget_tests/questionnaire_tests/questionnaire_test.dart".
I opened the link to the observatory.
I opened the timeline of the process.
I clicked all for Recorded Streams Profile
I opened the debugger of the main isolate.
I pressed F7 to continue the isolate.
I refreshed the timeline.
I saved the timeline.

Here is the saved timeline:
dart-timeline-2020-11-13 (1).json.zip
Trying to understand how to profile correctly
In order to provide you with a timeline file, I need to better understand what exactly I should do. So here are the parts broken down:

It should be possible to profile a test run from the flutter tool by starting it in the debugger...

How can I start the test run in the debugger? Do you mean opening the debugger in the observatory? I haven't found anything, where I would be able to start it from there.

then attaching to the debugger

How can I attach to the debugger, shouldn't I attache the debugger to a process?

enabling the profiler

Where can I do that? Is the "cpu profile" meant here or the timeline again?

The debugCheckIntrinsicSizeshelped already a lot. Do you have other expensive checks in mind, which can be disabled? Or other ideas how we can improve the speed, that wouldn't need improvement in the framework? What are the common things that make tests slow (we don't have any runAsync statements)?
Again thank you very very much. I apologize for my little knowledge, but I am trying as much as I can to help solve this issue.
Best,
Niklas

What you did with the timeline is perfect; for profiling it's basically the same thing but with the "CPU profile" option instead of the timeline. (I forget exactly what the UI looks like, it's been a while since I've done it. Sorry.)

Could you post a code snippet for the debugCheckIntrinsicSize change? I tried defining a subclass but when I instantiate I get an assertion failure. I'd like to see if it speeds up the ~1800 tests I'm running.

Could you post a code snippet for the debugCheckIntrinsicSize change? I tried defining a subclass but when I instantiate I get an assertion failure. I'd like to see if it speeds up the ~1800 tests I'm running.

class AutomatedTestWidgetsFlutterBindingWithCheckIntrinsicSizesDisabled
    extends AutomatedTestWidgetsFlutterBinding {
  @override
  bool get checkIntrinsicSizes => false;
}

Before each test instanciate the class like this:
AutomatedTestWidgetsFlutterBindingWithCheckIntrinsicSizesDisabled();

class AutomatedTestWidgetsFlutterBindingWithCheckIntrinsicSizesDisabled
    extends AutomatedTestWidgetsFlutterBinding {
  @override
  bool get checkIntrinsicSizes => false;
}

Before each test instanciate the class like this:
AutomatedTestWidgetsFlutterBindingWithCheckIntrinsicSizesDisabled();

Thank you! I had the code right but was putting it in the wrong place. I had put it in the setup() method instead of at the main() level. Working now.
On my ~1800 tests there was no appreciable performance difference. I tried it with this
  bool get checkIntrinsicSizes => true;

to verify and the tests took 2:12 with false and 2:14 with true. This is with version 1.22.5 from the stable channel.

Thank you! I had the code right but was putting it in the wrong place. I had put it in the setup() method instead of at the main() level. Working now.
On my ~1800 tests there was no appreciable performance difference. I tried it with this
  bool get checkIntrinsicSizes => true;

to verify and the tests took 2:12 with false and 2:14 with true. This is with version 1.22.5 from the stable channel.

How much of a difference the intrinsic asserts make really depends on how much layout is happening in your unit tests. For what it's worth, we are disabling those by default now.

How much of a difference the intrinsic asserts make really depends on how much layout is happening in your unit tests. For what it's worth, we are disabling those by default now.

Hello there!
I've been periodically checking the (lack of) activity on this issue. It seems we've narrowed down the scope of the discussion quite a bit. Even so, It seems it didn't lead to an effective solution for both this specific conversation and the original message posted.
I can report that for us, a suite of 350 tests (most being side effects free, very few with (filesystem) side effects) takes between 10 and 15 seconds to run. For anyone running the test suite frequently, sometimes up to once per minute, it's hard not to have one's mind wander, thereby losing focus or flow. In other programming landscapes, 2 orders of magnitude faster test suites are achieved without even trying. Why is it so slow in Dart? What can we do?
It seems that poor test performance have been reported for years now, yet still receives little focus from the flutter/dart team(s). Proof of this is that this ticket created about 10 months ago is still just one of the 3330 P4 tickets...
Love,
Séb

As shown by my following comment, the overhead is actually worse.
Also, that issue you linked is about that specific problem, but this issue is more general. The tests are too slow even without that one issue. So I don't think this should be closed even if this issue were resolved.

Agreed, until a real change is visible in the stable channel, It feels odd to "close" the issue.

Ya sorry I hadn't read the full context of the issue :). The change in the test package is very specifically geared towards regular Dart tests also, and has no effect on flutter tests. It should provide a dramatic improvement for regular Dart tests though 👍 .
I believe that flutter tests are already optimized using similar means (it is what inspired the VM test optimization). So if you are experiencing slow flutter tests I would look at the flutter test platform code and/or flutter test utilities.

Just wanted to add that the most problematic for us is the performance of coverage reporting tests on CI. For example a suite of 1400 tests takes over 20 minutes to finish. In other words it's about 1 second per test. It doesn't help much to cache build artifacts or dependencies. This really slows down the loop when doing the code reviews. We're looking into sharding the tests between multiple parallel runs, but in practice we wish it was just faster to run tests with coverage.

Coverage being slow is a separate issue (it requires changes to different parts of the codebase). We've made significant improvements over the past year to the coverage (mostly around accuracy, but also performance), but if you are still running into performance issues please file a bug specifically on that. If you have specific tests we can run that demonstrate the problem that is ideal (the Flutter framework tests are probably a good place to start if your project isn't open source itself).

authors: AlexMcConnell HerrNiklasRaab Hixie jakemac53 orestesgaolin pedromassangocode sowens-csd svarlet


text:
Navigator 2.0: Pressing Back Button on Android returns Black/White Screen

Steps to Reproduce

Run Navigator 2.0 example on Android Emulator or on a real Android device.
Navigate to the Settings or stay at the Home tab.
Press the back button.

Expected results:
Stay at /home or  navigate to /home from /settings page.
Actual results:
White/Black empty screen.

Logs
🚀: flutter analyze
Running "flutter pub get" in navigator_2_back_bug...               392ms
Analyzing navigator_2_back_bug...
No issues found! (ran in 2.8s)

🚀: flutter doctor -v
[✓] Flutter (Channel beta, 1.24.0-10.2.pre, on Mac OS X 10.15.7 19H2 darwin-x64, locale en-DE)
    • Flutter version 1.24.0-10.2.pre at /Users/user/dev/flutter
    • Framework revision 022b333a08 (4 days ago), 2020-11-18 11:35:09 -0800
    • Engine revision 07c1eed46b
    • Dart version 2.12.0 (build 2.12.0-29.10.beta)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/user/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • ANDROID_HOME = /Users/user/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (3 available)
    • Android SDK built for x86 (mobile) • emulator-5554 • android-x86    • Android 7.0 (API 24) (emulator)
    • Web Server (web)                   • web-server    • web-javascript • Flutter Tools
    • Chrome (web)                       • chrome        • web-javascript • Google Chrome 87.0.4280.67

• No issues found!

I resolve it using this code:
Navigator.pushReplacementNamed(context, '/route')

@hello-addweb Thanks, but I think this behavior should be fixed on the Flutter level or clarified by Flutter team.

@minikin
Tried the navigator gist on Android emulator (api 30) and on physical device (8.1.0), but didn't see the white / black empty screen after pressing back button.
71038_sim.mov.zip

beta flutter doctor -v

[✓] Flutter (Channel beta, 1.24.0-10.2.pre, on Mac OS X 10.15.4 19E2269
    darwin-x64, locale en-IN)
    • Flutter version 1.24.0-10.2.pre at /Users/dhs/documents/Fluttersdk/flutter
    • Framework revision 022b333a08 (5 days ago), 2020-11-18 11:35:09 -0800
    • Engine revision 07c1eed46b
    • Dart version 2.12.0 (build 2.12.0-29.10.beta)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
    • Android SDK at /Users/dhs/Library/Android/sdk
    • Platform android-30, build-tools 30.0.0
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.0.1, Build version 12A7300
    • CocoaPods version 1.9.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 46.0.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build
      1.8.0_242-release-1644-b3-6222593)

[✓] VS Code (version 1.50.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.15.1

[✓] Connected device (4 available)
    • SM A260G (mobile)                   • 5200763ebcfa861f
      • android-arm    • Android 8.1.0 (API 27)
    • iPhone SE (2nd generation) (mobile) • 6C85835D-FBFD-4AB3-8DE8-B4FAD35E5367
      • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-0 (simulator)
    • Web Server (web)                    • web-server
      • web-javascript • Flutter Tools
    • Chrome (web)                        • chrome
      • web-javascript • Google Chrome 87.0.4280.67

• No issues found!

Not sure if I missed anything to replicate the issue correctly ?

@darshankawar Thank you for checking out. It indeed works like on your video on the latest beta.
I also tested with 1.22.0-12.1.pre, and I still can reproduce the black screen, but I don't think that's important anymore.
So I'm closing the issue. Thanks again for your help!

authors: darshankawar hello-addweb minikin