Rudransh Singh Mahra
Rudransh Singh Mahra

Reputation: 115

Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'

I am developing a AI music player . But I am facing an error that i.e Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'. Help me in the 17,18,19 line of the code Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'.

Here is my code.I tried adding the late keyword but then I am facing casterror null check operator used on null value. So If possible please attach the corrected code also .

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,
      ),
    );
  }
}

Upvotes: 0

Views: 979

Answers (1)

nvoigt
nvoigt

Reputation: 77354

Well, we don't know what value you want those variables to have.

You can either initialize them to a value of your choice, or mark them as late and initialize them before you use them the first time, or you can make them nullable (by declaring them as Color? _selectedColor; for example) and then write your code in a way that takes into account that there might not be a value when you access them.

Either way, it's a choice you have to make. We cannot just pull a random value out of thin air and tell you to use it as initial value.

Upvotes: 1

Related Questions