Repository: flutter
Issue: ImageCache is reset to zero when I open iOS plugin by MethodChannel
Labels: platform-ios,framework,a: existing-apps,a: images,has reproducible steps,P2,found in release: 3.3,found in release: 3.5,team-ios,triaged-ios

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

Hi.
I am trying to use iOS image picker plugin in my Flutter using MethodChannel.
But I found that if I open and close the image picker(`My Image Picker` button), ImageCache is reset to zero.
So NetworkImage gets loading again like it has never been downloaded before.
On the other hand, Flutter's image picker(`Flutter Image Picker` button) doesn't reset ImageCache to zero so it is fine.
Why is this happening? Did I miss something?
I have tried overriding ImageCache size like below but the problem is not solved:

<img width="408" alt="image" src="https://user-images.githubusercontent.com/71176533/194592436-c9d68a50-6d3a-4de7-b9ae-eee1d63573fb.png">


Please help me...


<img height="600" alt="image" src="https://user-images.githubusercontent.com/71176533/194590154-bb2f0aa7-9768-4ba5-aeb3-3a9dec220e36.png"> <img height="600" alt="image" src="https://user-images.githubusercontent.com/71176533/194572609-4e5cdd6e-2922-4d4c-9ada-1628071ab376.png">
<img height="600" alt="image" src="https://user-images.githubusercontent.com/71176533/194591112-dec704fc-410b-49e0-b946-dc9c8f106ace.png"> <img height ="600" alt="image" src="https://user-images.githubusercontent.com/71176533/194591342-d66c436a-c2ea-455f-a109-b5da89769e30.png"> 






## Steps to Reproduce

<!-- Please include full steps to reproduce so that we can reproduce the problem. -->

1. Execute `flutter run` on the code sample <!-- (see "Code sample" section below) -->
2. Go to "star" tab on the Bottom Navigation
3. Wait until NetworkImage is downloaded and showing Ironman
4. Go back to "home" tab and press "My Image Picker" button
5. Close the image picker and go to "star" tab again
6. Image cache is gone(reset) and NetworkImage is downloaded again

| Expected results | Actual results |
| --------------- | --------------- |
<img width="400" src="https://user-images.githubusercontent.com/71176533/194572609-4e5cdd6e-2922-4d4c-9ada-1628071ab376.png"> | <img width="400" src="https://user-images.githubusercontent.com/71176533/194572999-24eae3c1-52ad-44eb-9977-70e1cbe38214.png">

<details>
<summary>Code sample</summary>

<!--
      Please create a minimal reproducible sample that shows the problem
      and attach it below between the lines with the backticks.

      To create it you can use `flutter create bug` command and update the `main.dart` file.

      Alternatively, you can use https://dartpad.dev/
      which is capable of creating and running small Flutter apps.

      Without this we will unlikely be able to progress on the issue, and because of that
      we regretfully will have to close it.
-->

```dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

class CustomImageCache extends WidgetsFlutterBinding {
  @override
  ImageCache createImageCache() {
    print('createImageCache start');
    ImageCache imageCache = super.createImageCache();
    // Set your image cache size
    imageCache.maximumSizeBytes = 9000000000000000000;
    imageCache.maximumSize = 9000000000000000000;
    return imageCache;
  }
}

void main() {
  CustomImageCache();
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final List<Widget> _navigationItems = [
    Home(),
    Star(),
  ];
  int _index = 0;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(),
        body: _navigationItems[_index],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _index,
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: "home",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.star),
              label: "star",
            ),
          ],
          onTap: (index) {
            setState(() {
              _index = index;
            });
          },
        ),
      ),
    );
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("currentSize : ${imageCache.currentSize}");
    print("currentSizeBytes : ${imageCache.currentSizeBytes}");

    return Center(
      child: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                ImagePicker picker = ImagePicker();
                picker.pickImage(source: ImageSource.gallery);
              },
              child: Text("Flutter Image Picker")),
          ElevatedButton(
              onPressed: () async {
                var result = await MethodChannel("test").invokeMethod("test");
                // Navigator.of(context).push(MaterialPageRoute(
                //   builder: (context) => IOSCompositionWidget(),
                // ));
              },
              child: Text("My Image Picker")),
        ],
      ),
    );
  }
}

class Star extends StatelessWidget {
  const Star({Key? key}) : super(key: key);
  final String _imageUrl = "https://www.wallpaperuse.com/wallp/9-93883_m.jpg";

  @override
  Widget build(BuildContext context) {
    print("currentSize : ${imageCache.currentSize}");
    print("currentSizeBytes : ${imageCache.currentSizeBytes}");

    return Container(
      child: Center(
        child: Image(
          image: NetworkImage(_imageUrl),
          fit: BoxFit.fill,
        ),
      ),
    );
  }
}
```
```swift
import UIKit
import Flutter
import YPImagePicker
import AVFoundation
import AVKit
import Photos

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    var navigationController: UINavigationController!
    
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    GeneratedPluginRegistrant.register(with: self)
      
       let controller = window?.rootViewController as! FlutterViewController
       self.navigationController = UINavigationController(rootViewController: controller)
       self.window.rootViewController = self.navigationController
       self.navigationController.setNavigationBarHidden(true, animated: false)
       self.window.makeKeyAndVisible()
       let methodChannel = FlutterMethodChannel(name: "test", binaryMessenger:controller.binaryMessenger)

       methodChannel.setMethodCallHandler({
         (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in

         if call.method == "test" {
             func resolutionForLocalVideo(url: URL) -> CGSize? {
                 guard let track = AVURLAsset(url: url).tracks(withMediaType: AVMediaType.video).first else { return nil }
                 let size = track.naturalSize.applying(track.preferredTransform)
                 return CGSize(width: abs(size.width), height: abs(size.height))
             }
             func showPicker() {
                 var config = YPImagePickerConfiguration()
                 config.targetImageSize = YPImageSize.cappedTo(size: 256)
                 config.startOnScreen = YPPickerScreen.library
                 config.screens = [.library, .photo]
                 config.overlayView = UIView()
                 config.library.minWidthForItem = 1
                 let picker = YPImagePicker(configuration: config)
                 picker.didFinishPicking { [weak picker] items, cancelled in

                     if cancelled {
                         print("Picker was canceled")
                         picker?.dismiss(animated: true, completion: nil)
 //                        self.navigationController?.popViewController(animated: true)
                         result(nil)
                     }
                     _ = items.map { print("🧀 \($0)") }

                     if let firstItem = items.first {
                         switch firstItem {
                         case .photo(let photo):
                             picker?.dismiss(animated: true, completion: nil)
 //                            self.navigationController?.popViewController(animated: true)
                             result(nil)
                         case .video(let video):
                             let assetURL = video.url
                             let playerVC = AVPlayerViewController()
                             let player = AVPlayer(playerItem: AVPlayerItem(url:assetURL))
                             playerVC.player = player

                             picker?.dismiss(animated: true, completion: { [weak self] in
                             print("😀 \(String(describing: resolutionForLocalVideo(url: assetURL)!))")
                             })
 //                            self.navigationController?.popViewController(animated: true)
                             result(nil)
                         }
                     }
                 }

                 self.navigationController?.setNavigationBarHidden(true, animated: true)
                 self.navigationController?.present(picker, animated: true, completion: nil)
 //                self.navigationController?.pushViewController(picker, animated: true)

             }
             showPicker()
         } else {
           result(FlutterMethodNotImplemented)
           return
         }
       })
//      weak var registrar = self.registrar(forPlugin: "plugin-name")
//
//      let factory = FLNativeViewFactory(messenger: registrar!.messenger())
//      self.registrar(forPlugin: "<plugin-name>")!.register(factory, withId: "<platform-view-type>")
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

```

</details>

<details>
  <summary>Logs</summary>

<!--
      Run your application with `flutter run --verbose` and attach all the
      log output below between the lines with the backticks. If there is an
      exception, please see if the error message includes enough information
      to explain how to solve the issue. If there is a crash, please include
      the entirety of the crash log including the backtrace.
-->

```
```
`flutter run --verbose` log is too long, so Github doesn't allow to post this issue
> There was an error creating your Issue: body is too long, body is too long (maximum is 65536 characters).

<!--
     Run `flutter analyze` and attach any output of that command below.
     If there are any analysis errors, try resolving them before filing this issue.
-->

```
   info • The import of 'package:flutter/widgets.dart' is unnecessary because all of the used elements are also provided by the import of 'package:flutter/material.dart' •
          lib/home.dart:3:8 • unnecessary_import
   info • Avoid `print` calls in production code • lib/main.dart:8:5 • avoid_print
   info • Prefer declaring const constructors on `@immutable` classes • lib/main.dart:23:3 • prefer_const_constructors_in_immutables
   info • Prefer const with constant constructors • lib/main.dart:31:5 • prefer_const_constructors
   info • Prefer const with constant constructors • lib/main.dart:32:5 • prefer_const_constructors
   info • Avoid `print` calls in production code • lib/main.dart:75:5 • avoid_print
   info • Avoid `print` calls in production code • lib/main.dart:76:5 • avoid_print
   info • Prefer const with constant constructors • lib/main.dart:86:22 • prefer_const_constructors
   info • The value of the local variable 'result' isn't used • lib/main.dart:89:21 • unused_local_variable
   info • Prefer const with constant constructors • lib/main.dart:89:36 • prefer_const_constructors
   info • Prefer const with constant constructors • lib/main.dart:94:22 • prefer_const_constructors
   info • Avoid `print` calls in production code • lib/main.dart:107:5 • avoid_print
   info • Avoid `print` calls in production code • lib/main.dart:108:5 • avoid_print
   info • Avoid unnecessary containers • lib/main.dart:110:12 • avoid_unnecessary_containers

14 issues found. (ran in 4.0s)

```

<!-- Finally, paste the output of running `flutter doctor -v` here. -->

```
[✓] Flutter (Channel stable, 3.3.2, on macOS 12.3.1 21E258 darwin-x64, locale ko-KR)
    • Flutter version 3.3.2 on channel stable at /Users/jwpark_imac/install/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision e3c29ec00c (3주 전), 2022-09-14 08:46:55 -0500
    • Engine revision a4ff2c53d8
    • Dart version 2.18.1
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/jwpark_imac/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13F100
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.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 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.69.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • iPhone 12 Pro (mobile) • F783F39F-4581-481F-A9D4-7CD145AFE414 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-0 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     • macOS 12.3.1 21E258 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 105.0.5195.125

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

```

</details>


<!--
      Consider also attaching screenshots and/or videos to better
      illustrate the issue.

      You can upload them directly on GitHub.
      Beware that video file size is limited to 10MB.
-->