Skip to content

Commit 587ee23

Browse files
authored
[shared_preferences] Defer SharedPreferences fetch in LegacySharedPreferencesPlugin until first use on Android (flutter#13431)
Defers `getSharedPreferences` in `LegacySharedPreferencesPlugin` out of `onAttachedToEngine` until first use, avoiding synchronous disk I/O on the Android main thread during startup. The following screenshot shows that the time taken for `RegisterFlutterPlugin` significantly decreases with the change, which validates the fix: <img width="1920" height="552" alt="shared_preferences_registration_comparison_perfetto" src="https://github.com/user-attachments/assets/c1fea032-a499-4fa4-91de-13648ea03999" /> I also previously implemented this in my app, which was later negated by an upgrade of the shared_preferences packages into g3 and caused cold startup latency regression alerts on my app. Hoping to upstream the fix to get this optimization to all Flutter users. flutter#195313 will be fixed by this PR. ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent d155a33 commit 587ee23

4 files changed

Lines changed: 35 additions & 3 deletions

File tree

‎packages/shared_preferences/shared_preferences_android/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 2.5.4
2+
3+
* Fixes eager SharedPreferences fetch in `LegacySharedPreferencesPlugin` executing synchronous disk I/O on Android main thread during startup by deferring the fetch until first use.
4+
15
## 2.5.3
26

37
* Fixes web compilation of apps that import `package:shared_preferences_android`, for example to use `SharedPreferencesAsyncAndroidOptions`.

‎packages/shared_preferences/shared_preferences_android/android/src/main/kotlin/io/flutter/plugins/sharedpreferences/LegacySharedPreferencesPlugin.kt‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,17 @@ class LegacySharedPreferencesPlugin
2929
@VisibleForTesting
3030
internal constructor(private val listEncoder: SharedPreferencesListEncoder) :
3131
FlutterPlugin, SharedPreferencesApi {
32-
private lateinit var preferences: SharedPreferences
32+
private lateinit var context: Context
33+
private val preferences: SharedPreferences by lazy {
34+
context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
35+
}
36+
3337
private val backgroundDispatcher = Dispatchers.IO.limitedParallelism(1)
3438

3539
constructor() : this(ListEncoder())
3640

3741
private fun setUp(context: Context) {
38-
preferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
42+
this.context = context
3943
try {
4044
SharedPreferencesApiRegistrar().register(this)
4145
} catch (ex: Exception) {

‎packages/shared_preferences/shared_preferences_android/android/src/test/kotlin/io/flutter/plugins/sharedpreferences/LegacySharedPreferencesTest.kt‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,30 @@ class LegacySharedPreferencesTest {
3939
plugin.onAttachedToEngine(flutterPluginBinding)
4040
}
4141

42+
@Test
43+
fun onAttachedToEngine_doesNotEagerlyInitializePreferences(): Unit = runBlocking {
44+
val mockContext = Mockito.mock(Context::class.java)
45+
val binding = Mockito.mock(FlutterPluginBinding::class.java)
46+
Mockito.`when`(binding.applicationContext).thenReturn(mockContext)
47+
Mockito.`when`(
48+
mockContext.getSharedPreferences(
49+
ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()))
50+
.thenReturn(FakeSharedPreferences())
51+
52+
val testPlugin = LegacySharedPreferencesPlugin(ListEncoder())
53+
testPlugin.onAttachedToEngine(binding)
54+
55+
// SharedPreferences should not be fetched during onAttachedToEngine to avoid main-thread disk
56+
// I/O.
57+
Mockito.verify(mockContext, Mockito.never())
58+
.getSharedPreferences(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt())
59+
60+
// First call to any API method lazily initializes preferences.
61+
testPlugin.getAll("", null)
62+
Mockito.verify(mockContext, Mockito.times(1))
63+
.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
64+
}
65+
4266
@Test
4367
fun getAll() = runBlocking {
4468
assertEquals(0, plugin.getAll("", null).size)

‎packages/shared_preferences/shared_preferences_android/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: shared_preferences_android
22
description: Android implementation of the shared_preferences plugin
33
repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_android
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
5-
version: 2.5.3
5+
version: 2.5.4
66

77
environment:
88
sdk: ^3.12.0

0 commit comments

Comments
 (0)