HDD
HDD

Reputation: 260

Error: The getter 'length' was called on null

Error says: NoSuchMethodError: The getter 'length' was called on null

It is a basic flutter music player App.

main.dart

import 'package:flute_music_player/flute_music_player.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Song> _songs;
  @override

  void initState() {
    // TODO: implement initState
    super.initState();
    initPlayer();
  }

  void initPlayer() async{
    var songs = await MusicFinder.allSongs();
    songs=new List.from(songs);
    setState(() {
      _songs = songs;
    });
  }


  @override

  Widget build(BuildContext context) {

      Widget home(){
        new Scaffold(
          appBar: new AppBar(title: new Text("Music App"),

          ),
          body: new ListView.builder(
              itemCount: _songs.length,
              itemBuilder: (context,int index){
                return new ListTile(
                  leading: new CircleAvatar(
                    child: new Text(_songs[index].title[0]),
                  ),
                  title: new Text(_songs[index].title),
                );
              }),
        );
      }



    return new MaterialApp(
      home: home(),
    );
  }
}

pubspec.yaml

name: music_player
description: A new Flutter application.
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  flute_music_player:

dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true

It should show the list of musics as result but gives an unexpected error.I am running on android.Plz help me out.

It should show the list of musics as result but gives an unexpected error.I am running on android.Plz help me out.

Upvotes: 2

Views: 4421

Answers (2)

Sergio Bernal
Sergio Bernal

Reputation: 2327

Since you're performing an async operation, that would take certain amount of time so when your app first builds, the songs array is null. Try to start with an empty array instead of a null array: List<Song> _songs = []; then, when the async operation is completed the setState will make the widget to rebuild and show the array with data.

Upvotes: 1

Andrii Turkovskyi
Andrii Turkovskyi

Reputation: 29468

Change itemCount: _songs.length to itemCount: _songs?.length ?? 0 - it helps to avoid exception

Upvotes: 9

Related Questions