Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting "NoSuchMethodError: The method 'toImage' was called on null." Exception #42

Closed
tehsunnliu opened this issue May 15, 2021 · 6 comments
Assignees

Comments

@tehsunnliu
Copy link

tehsunnliu commented May 15, 2021

screenshot: ^0.2.0 was working perfectly fine till I updated Flutter to 2.0 and Screenshot Package to screenshot: ^1.0.0-nullsafety.1 I started getting "NoSuchMethodError: The method 'toImage' was called on null." exception.
I'm calling screenshotController.capture() method.
The exception is thrown inside captureAsUiImage() method when it tries to call boundary.toImage(...);

This happens when I try to capture multiple widgets screenshot.
I've multiple CardView inside a Column which is wrapped with Screenshot widget. When I try to all .capture() for each ScreenshotController only the first call to capture works and for the rest it throws NoSuchMethodError
I've also tried increasing the delay, however, no success.

@tehsunnliu
Copy link
Author

It seems for some reason this._containerKey.currentContext is null in captureAsUiImage(...). Anyways I used RepaintBoundary instead and got it working.

@ritheshSalyan
Copy link
Collaborator

@tehsunnliu Can I get the minimum code to reproduce this issue? Did you wrap your widget with Screenshot Widget?

@tehsunnliu
Copy link
Author

tehsunnliu commented May 17, 2021

@ritheshSalyan Hi, Thank you for your response. First of all my apologies. I should have tested my code more before opening an issue. While I was writing a sample code to reproduce the error I mentioned. I found that I was calling setState() before calling screenshotController.capture(...) which called build() function. And in build function, I've added _screenshotControllers.clear(); which clears all the ScreenshotController in that list. Hence, throwing NoSuchMethodError.

However, this same implementation works fine with RepaintBoundary. I'm not sure how this doesn't affect RepaintBoundary.

Anyways below is the code which throws NoSuchMethodError.

import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.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(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  bool _isSaving = false;
  List<ScreenshotController> _screenshotControllers = [];
  List<Widget> _widgets = [
    Card(
      child: ListTile(
        leading: Icon(
          Icons.person,
        ),
        title: Text('Testing Screenshot 1'),
      ),
    ),
    Card(
      child: ListTile(
        leading: Icon(
          Icons.person,
        ),
        title: Text('Testing Screenshot 2'),
      ),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    _screenshotControllers.clear();

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: _widgets.map((e) {
            ScreenshotController controller = ScreenshotController();
            _screenshotControllers.add(controller);
            return Screenshot(
              controller: controller,
              child: e,
            );
          }).toList(),
        ),
      ),
      floatingActionButton: _isSaving
          ? CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(Colors.white),
            )
          : FloatingActionButton(
              onPressed: _saveWidgets,
              tooltip: 'Save',
              child: Icon(Icons.save),
            ),
    );
  }

  void _saveWidgets() async {
    setState(() {
      _isSaving = true;
    });
    try {
      for (int i = _screenshotControllers.length - 1; i >= 0; --i) {
        var data =
            await _screenshotControllers[i].capture(pixelRatio: 3);
        print('ScreenshotData: $data');
      }
    } catch (e) {
      print('failed to capture: $e');
      debugPrintStack();
    }
    setState(() {
      _isSaving = false;
    });
  }
}

@ritheshSalyan
Copy link
Collaborator

ritheshSalyan commented May 17, 2021

@tehsunnliu The code you have shared is working perfectly fine, It didn't throw any error,
Here Is the video Proof for working.
https://user-images.githubusercontent.com/44966372/118475356-c913eb00-b729-11eb-9a55-f7d6207652f5.mp4

Can I know your flutter version?

You can close this issue if it is working.

@tehsunnliu
Copy link
Author

tehsunnliu commented May 17, 2021

Oh, I don't know why it's happening with me with the same code I haven't changed anything. Have you tried on debug mode?
I'll share the Flutter version as soon as I get access to my pc.
Thank you.

@tehsunnliu
Copy link
Author

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.6, on Linux, locale en_IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Chrome - develop for the web
[✓] Android Studio
[✓] Connected device (1 available)

• No issues found!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants