首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >_CastError (尝试播放歌曲时对空值使用的空值检查运算符)

_CastError (尝试播放歌曲时对空值使用的空值检查运算符)
EN

Stack Overflow用户
提问于 2021-11-01 17:40:35
回答 1查看 79关注 0票数 0

我面对的是_CastError,我无法修复它。如果任何人可以纠正现有的代码,并附加它,将非常感谢。我已经使用了!运算符,我认为这是这个问题的主要原因。我不知道如何处理这个问题。一个更正的代码和附件将非常感谢这里是我的代码:我也附上了错误截图,所以请看一看。

_CastError ScreenShot

代码语言:javascript
复制
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,
      ),
    );
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-01 19:24:17

你希望我只给你正确的代码,不幸的是,这并不是那么简单,我不知道如何修复代码,因为我不知道你想要发生什么,但我可以给你建议,我可以解释这些建议的利弊:

代码语言:javascript
复制
_audioPlayer.play(_selectedRadio!.url);

在这一行中出现错误意味着_selectedRadio为null,这意味着url不是一个东西。

在阅读您的代码后,我注意到您只在e playMusic方法上赋值_selectedRadio,但我没有看到您调用该方法,因此您有三个选择:

首先,您可以为_selectedRadio指定一个缺省值,使其永远不会为null

发自:

代码语言:javascript
复制
MyRadio? _selectedRadio;

至:

代码语言:javascript
复制
MyRadio _selectedRadio = MyRadio(); // I don't know how you initialize this

第二:可以检查_selectedRadio是否为` `null

发自:

代码语言:javascript
复制
} else {
  _audioPlayer.play(_selectedRadio!.url);
}

转到;

代码语言:javascript
复制
} else {
  if (_selectedRadio != null) {
    _audioPlayer.play(_selectedRadio!.url);
  }
}

最后,如果_selectedRadionull,您可以提供一些后备值来播放

发自:

代码语言:javascript
复制
_audioPlayer.play(_selectedRadio!.url);

至:

代码语言:javascript
复制
_audioPlayer.play(_selectedRadio?.url ?? 'some other url');

你的决定取决于你想让你的应用程序做什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69800647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档