Open clragon opened 11 months ago
Further, I have found out that I can work around this issue with the following code:
await Uri.parse('${folder.uri}%2F${Uri.encodeComponent(fileName)}')).toDocumentFile();
which is basically just manually constructing the same URI and then converting it into a DocumentFile
.
For whatever reason, this does not trigger a findFile
call and therefore doesnt run into the ANR issue.
However, I would obviously strongly prefer constructing files with the intended APIs and not manually.
Hi! I could reproduce here as well, thank you very much for the detailed issue.
findFiles
is flawed by design, it's a brute force search implemented by the android sdk (a simple linear search) which is a performance disaster when we have a folder with several files (which is the case for the vast majority of the modern devices).
About your workaround, it won't work with some edgy content providers because sometimes the URI doesn't follow the
parent/child.ext
naming pattern but a provider_storage_id/document_id
pattern.
I'll try to fix it using content providers and manually query the storage DB, but in the worst scenario we can just run the findFiles method in a background thread (it will still be slow but will fix the main thread blocking).
Describe the bug
Using
DocumentFile.findFile
inside of a folder with many files will somehow use so much CPU that it hangs the main UI thread.To Reproduce
Note that the sample code actually uses
DocumentFile.child
but this triggers an unreasonably costlyfindFile
regardless.Sample code
```dart import 'package:flutter/material.dart'; import 'package:shared_storage/shared_storage.dart'; void main() => runApp(const App()); class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( colorScheme: ColorScheme.fromSeed( brightness: Brightness.dark, seedColor: Colors.deepPurple, ), useMaterial3: true, ), home: const Home(), ); } } class Home extends StatefulWidget { const Home({super.key}); @override StateExpected behavior
Using
DocumentFile.findFile
should not hang the UI thread.Screenshots
Here is a video demonstration of the issue:
https://github.com/alexrintt/shared-storage/assets/11785085/21d9f96f-279c-4ce2-aa1b-4d50ffbde3c6
Smartphone: