aneel ilyas
aneel ilyas

Reputation: 41

The getter 'length' was called on null flutter?

Hello anyone know how to handle null exception before loading data from api i have an app which load data from api before loading it shows me. This error

The getter 'length' was called on null.
Receiver: null
Tried calling: length

and when data is load the error will gone please help me how i used prorgressbar bar before data is not loading i am trying to fetch data from api when api fetch data it pass data in List userdata variable and called widget webview problem is that before loading it show length' was called on null after loading it working fine please check my code and help me

here my code

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:youtube_player_flutter/youtube_player_flutter.dart';

class Media extends StatefulWidget {
  @override
  _MediaState createState() => _MediaState();
}

class _MediaState extends State<Media> {

  void initState() {
getData();
    super.initState();
  }
  bool _loading=true;
  Map data;
  List userData=null;
  Future getData() async {
    http.Response response = await http.get("https://livinghopemobile.com/public/api/fetch-livetv?token=123ab_@_@AbCD");
    data = json.decode(response.body);
    debugPrint(response.body);
    setState(() {
      userData = data["data"];
      _loading=false;
     // print(userData[0]['title']);
    });

  }


  @override
  Widget build(BuildContext context) {


    return Mediaplayer();



  }
  Mediaplayer() {
    final Completer<WebViewController> _controller = Completer<WebViewController>();
    var url =userData[0]['link'];

    String externalurl = '''
<!doctype html>
<html>
<head>
<link href="https://vjs.zencdn.net/7.10.2/video-js.css" rel="stylesheet" />

  <!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->

</head>

<body>
<center>
 <video
    id="my-video"
    class="video-js vjs-big-play-centered"
    controls
    preload="auto"
    width="1000"
    height="400"
    poster="http://lhtvapp.com/click.png"
    data-setup="{}"
  >
    <source src="$url" type="application/x-mpegURL"/>

    <p class="vjs-no-js">
      To view this video please enable JavaScript, and consider upgrading to a
      web browser that
      <a href="https://videojs.com/html5-video-support/" target="_blank"
        >supports HTML5 video</a
      >
    </p>
  </video>
  </center>

<script src="https://vjs.zencdn.net/7.10.2/video.min.js"></script>
</body>


</body>
</html
''';


    if (url.contains('.mp4')||url.contains('.m3u8')) {


      return
        _loading?Center(
        child:CircularProgressIndicator(),
      ):
      Container(
        child: WebView(
          initialUrl: Uri.dataFromString(externalurl , mimeType: 'text/html').toString(),
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
        ),
      );


    }
    else if(url.contains('https://www.youtube.com/')){
      String videoID= YoutubePlayer.convertUrlToId(url);

      String youtube = '''
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.plyr.io/3.6.2/plyr.css" />
<script src="https://cdn.plyr.io/3.6.2/plyr.polyfilled.js"></script>

<style>
.container {
    margin: 20px auto;
    max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
    <div id="player" data-plyr-provider="youtube" data-plyr-embed-id="$videoID"></div>
</div>

<script src="path/to/plyr.js"></script>
<script>
  const player = new Plyr('#player');
</script>


</body>
</html>
''';
      return
        _loading?Center(
        child:CircularProgressIndicator(),
      ):
        Container(
        child: WebView(
          initialUrl: Uri.dataFromString(youtube , mimeType: 'text/html').toString(),
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
        ),
      );

    }


  }
}

Upvotes: 0

Views: 1334

Answers (2)

aneel ilyas
aneel ilyas

Reputation: 41

I used simple solution until data is not load i used progress bar

return _loading?Center( child:CircularProgressIndicator( valueColor: new AlwaysStoppedAnimation(Colors.amberAccent), ), ):Mediaplayer();

Upvotes: 0

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

The problem is caused by your list userData. Not sure why you are giving it a value of null and asking for trouble, but you can assign it as an empty list.

Whenever you want to call that list or perform operations on it, you can check if it's null or has value. like this line in your code var url =userData[0]['link'];

change it into:

var url =userData != null && userData.isNotEmpty ? userData[0]['link'] : 'No link yet';

The error you are receiving is because to you are telling dart to access userData[0]['link'] ==> meaning that you tell it to go to list userData, then get the length of that list, after you are done getting that length, go the item at index [0], and access the ['link'] key and return it's value.

by checking that your list isn't null, you can avoid such errors.

While writing code, try to keep in mind the possible ways your code can break, and how to overcome it before hand, by checking for possible null values, it'll make your code more performant, less prone to bugs and errors as well. Consider migrating to null safety if you're just starting, you'll thank yourself for it in the near future. Happy coding.

Upvotes: 1

Related Questions