Home > Enterprise >  _CastError (Null check operator used on a null value) while trying to play song
_CastError (Null check operator used on a null value) while trying to play song

Time:11-02

I am facing _CastError and I am unable to fix it. If anyone can correct the existing code and attach it, it would be much appreciated. I have used the ! operator and I think it's the main reason for this issue. I don't know how to handle this issue . A corrected code and attached would be much appreciated Here is my Code: I am also attaching the error screenshot so please have a look.

_CastError ScreenShot

import 'package:ai_music_player/model/radio.dart';
import 'package:ai_music_player/utils/ai_utils.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:velocity_x/velocity_x.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  List<MyRadio>? radios;
  MyRadio? _selectedRadio;
  Color? _selectedColor;
  bool _isPlaying = false;

  final AudioPlayer _audioPlayer = AudioPlayer();

  @override
  void initState() {
    super.initState();
    fetchRadios();
    _audioPlayer.onPlayerStateChanged.listen((event) {
      if (event == PlayerState.PLAYING) {
        _isPlaying = true;
      } else {
        _isPlaying = false;
      }
      setState(() {});
    });
  }

  fetchRadios() async {
    final radioJson = await rootBundle.loadString("assets/radio.json");
    radios = MyRadioList.fromJson(radioJson).radios;
    setState(() {});
  }

  playMusic(String url) {
    _audioPlayer.play(url);
    _selectedRadio = radios!.firstWhere((element) => element.url == url);
    print(_selectedRadio!.name);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      body: Stack(
        children: [
          VxAnimatedBox()
              .size(context.screenWidth, context.screenHeight)
              .withGradient(
                LinearGradient(
                    colors: [AIColors.primaryColor1, AIColors.primaryColor2],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight),
              )
              .make(),
          AppBar(
            title: "AI Player".text.xl4.bold.white.make().shimmer(
                primaryColor: Vx.purple300, secondaryColor: Colors.white),
            backgroundColor: Colors.transparent,
            elevation: 0.0,
            centerTitle: true,
          ).h(120),
          radios != null
              ? VxSwiper.builder(
                  itemCount: radios!.length,
                  enlargeCenterPage: true,
                  itemBuilder: (context, index) {
                    final rad = radios![index];
                    return VxBox(
                      child: ZStack(
                        [
                          Positioned(
                            top: 0,
                            right: 0,
                            child: VxBox(
                              child: rad.lang.text.uppercase.bold.white
                                  .make()
                                  .px16(),
                            )
                                .height(40)
                                .black
                                .alignCenter
                                .withRounded(value: 10)
                                .make(),
                          ),
                          Align(
                            alignment: Alignment.bottomCenter,
                            child: VStack(
                              [
                                rad.name.text.xl5.white.bold.make(),
                                5.heightBox,
                                rad.tagline.text.xl.white.bold.italic.make(),
                              ],
                              crossAlignment: CrossAxisAlignment.center,
                            ),
                          ),
                          Align(
                            alignment: Alignment.center,
                            child: [
                              const Icon(
                                CupertinoIcons.play_circle,
                                color: Colors.white54,
                                size: 60,
                              ),
                              10.heightBox,
                              "DOUBLE TAB TO PLAY".text.gray300.make()
                            ].vStack(),
                          ),
                        ],
                      ),
                    )
                        .clip(Clip.antiAlias)
                        .bgImage(
                          DecorationImage(
                            image: NetworkImage(rad.image),
                            fit: BoxFit.cover,
                            colorFilter: ColorFilter.mode(
                                Colors.black.withOpacity(0.3),
                                BlendMode.darken),
                          ),
                        )
                        .border(color: Colors.black, width: 3)
                        .withRounded(value: 60.0)
                        .make()
                        .onInkDoubleTap(() {
                      _audioPlayer.play(rad.url);
                    });
                  },
                  aspectRatio: 1.0,
                ).centered()
              : const Center(
                  child: CircularProgressIndicator(
                    color: Colors.white,
                  ),
                ),
          Align(
            alignment: Alignment.bottomCenter,
            child: [
              if (_isPlaying)
                "Playing - ${_selectedRadio!.name} FM".text.makeCentered(),
              Icon(
                _isPlaying
                    ? CupertinoIcons.stop_circle
                    : CupertinoIcons.play_circle,
                color: Colors.white,
                size: 60,
              ).onInkTap(() {
                if (_isPlaying) {
                  _audioPlayer.stop();
                } else {
                  _audioPlayer.play(_selectedRadio!.url);
                }
              })
            ].vStack(),
          ).pOnly(bottom: context.percentHeight * 12)
        ],
        fit: StackFit.expand,
      ),
    );
  }
}

CodePudding user response:

You want me to just give you the corrected code, unfortunately, it's not so simple, I don't know how to fix the code, because I don't know what you want to happen, however I can give you recommendations and I can explain the pros and cons of such recommendations:

_audioPlayer.play(_selectedRadio!.url);

The fact that you get an error in this line means that _selectedRadio is null, and that means that url is not a thing.

After reading your code I noticed you only ever assign _selectedRadio on the e playMusic method, but I don't see you calling that method ever, so you have three options:

First, you can assign a default value to the _selectedRadio to make it never be null

from:

MyRadio? _selectedRadio;

to:

MyRadio _selectedRadio = MyRadio(); // I don't know how you initialize this

Second: You can check if _selectedRadio is `null

From:

} else {
  _audioPlayer.play(_selectedRadio!.url);
}

To;

} else {
  if (_selectedRadio != null) {
    _audioPlayer.play(_selectedRadio!.url);
  }
}

Finally, you could provide some fallback value to play if _selectedRadio is null

From:

_audioPlayer.play(_selectedRadio!.url);

To:

_audioPlayer.play(_selectedRadio?.url ?? 'some other url');

Your decision depends on what you want you app to do.

  • Related