Flutter - The method 'then' was called on null

4,379

You should try this :

Future<dynamic> eval(String js) async =>
  controller?.evaluateJavascript(js)?.catchError((_) => '');

void _getBottomPosition() async {
    final eval = await eval("(window.innerHeight + window.scrollY) >= document.body.offsetHeight");
    String bottmPosition = eval.toString() ?? '';
    isBottomPosition = bottmPosition;
    print("bottomPosition: " + isBottomPosition);
}

First add async keyword to eval method then update eval call in _getBottomPosition.

Share:
4,379
Amit Aisikowitz
Author by

Amit Aisikowitz

Updated on December 17, 2022

Comments

  • Amit Aisikowitz
    Amit Aisikowitz over 1 year

    I have a flutter project with 2 functions:

    Future<dynamic> eval(String js) =>
      controller?.evaluateJavascript(js)?.catchError((_) => '');
    
    void _getBottomPosition() async {
        final evals = await Future.wait([
            eval("(window.innerHeight + window.scrollY) >= document.body.offsetHeight"),
        ]);
        String bottmPosition = evals[0].toString() ?? '';
        isBottomPosition = bottmPosition;
        print("bottomPosition: " + isBottomPosition);
    }
    

    I'm getting the following error:

    E/flutter (14430): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'then' was called on null.
    E/flutter (14430): Receiver: null
    E/flutter (14430): Tried calling: then<Null>(Closure: (dynamic) => Null, onError: Closure: (dynamic, StackTrace) => Null)
    

    Can anyone help me solve this?

    Thanks.

    • Dennis
      Dennis over 4 years
      I don't really know Dart, but could take a guess from a different async background: Your method eval is not async, so it will return null as a result if controller is null, not a Future of null. This might be a problem for Future.wait, which will effectively become Future.wait([null])
    • Dennis
      Dennis over 4 years
      ... and if that guess is correct, you could resolve it by adding a default future to your eval implementation, like controller?.evaluateJavascript(js)?.catchError((_) => '') ?? Future.value<dynamic>(null), as described here: stackoverflow.com/questions/18423691/… But again, I have little experience with Dart.
    • Ketan Ramteke
      Ketan Ramteke over 4 years
      Future<dynamic> eval(String js) async{ return await controller?.evaluateJavascript(js)?.catchError((_) => '');}