Home > OS >  How to solve Null check operator used on a null value
How to solve Null check operator used on a null value

Time:12-02

I am trying to make a pdf downloader application that downloads a pdf from the given link when the user clicks the download button. But it continuously showing the error that the Null check operator used on a null value. I don't know where I have used a null check operator here Please help me.

Here Is My Code

import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _downloadFile() async {
    // final status = await Permission.storage.request();
    // if (status.isGranted) {
    if (FlutterDownloader.initialize() == true) {
      final baseStorage = await getExternalStorageDirectory();
      if (baseStorage != null) {
        final id = FlutterDownloader.enqueue(
            url:
                'https://drive.google.com/uc?export=download&id=1lJe77StiP9XU05l5N1TpFHYYZfdrPHYG',
            savedDir: baseStorage.path,
            fileName: 'Jony.pdf');
      }
      // } else {
      //   print("No Permission");
      // }
    }
  }

  ReceivePort receivePort = ReceivePort();
  int progress = 0;
  downloaderCallback(id, status, progress) {
    var sendPort = IsolateNameServer.lookupPortByName('pdfdownloadId');
    if (sendPort != null) {
      sendPort.send(progress);
    }
  }

  @override
  void initState() {
    // TODO: implement initState

    IsolateNameServer.registerPortWithName(
        receivePort.sendPort, 'pdfdownloadId');
    FlutterDownloader.registerCallback(downloaderCallback);
    receivePort.listen((message) {
      setState(() {
        progress = message;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Click To Download',
            ),
            Text(
              '$progress',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _downloadFile,
        tooltip: 'Click',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Here are my errors

The following _CastError was thrown building Builder:
Null check operator used on a null value

The relevant error-causing widget was
MaterialApp
package:flutter_application_downloader/main.dart:21
When the exception was thrown, this was the stack
#0      FlutterDownloader.registerCallback
package:flutter_downloader/src/downloader.dart:397
#1      _MyHomePageState.initState
package:flutter_application_downloader/main.dart:94
#2      StatefulElement._firstBuild
package:flutter/…/widgets/framework.dart:4893
#3      ComponentElement.mount
package:flutter/…/widgets/framework.dart:4729
...     Normal element mounting (171 frames)
#174    Element.inflateWidget
package:flutter/…/widgets/framework.dart:3790
#175    MultiChildRenderObjectElement.inflateWidget
package:flutter/…/widgets/framework.dart:6422
#176    MultiChildRenderObjectElement.mount
package:flutter/…/widgets/framework.dart:6433
...     Normal element mounting (377 frames)
#553    Element.inflateWidget
package:flutter/…/widgets/framework.dart:3790
#554    Element.updateChild
package:flutter/…/widgets/framework.dart:3540
#555    RenderObjectToWidgetElement._rebuild
package:flutter/…/widgets/binding.dart:1198
#556    RenderObjectToWidgetElement.mount
package:flutter/…/widgets/binding.dart:1167
#557    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure>
package:flutter/…/widgets/binding.dart:1112
#558    BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2600
#559    RenderObjectToWidgetAdapter.attachToRenderTree
package:flutter/…/widgets/binding.dart:1111
#560    WidgetsBinding.attachRootWidget
package:flutter/…/widgets/binding.dart:944
#561    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>
package:flutter/…/widgets/binding.dart:924
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)

I was trying to download a pdf file in my emulator through this code but it is showing me that null check operator used on a null value . and the error occured inside

FlutterDownloader.registerCallback(downloaderCallback);

CodePudding user response:

you are getting error in FlutterDownloader.registerCallback(downloaderCallback); cause may be registerCallback getting null. just add static void to your downloadCallback function.

 static void downloaderCallback(id, status, progress) {
    var sendPort = IsolateNameServer.lookupPortByName('pdfdownloadId');
    if (sendPort != null) {
      sendPort.send(progress);

    }
  }

may this can help you.

  • Related