错误说: NoSuchMethodError:在空值上调用了吸气剂“长度”
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
它应该显示音乐列表,但会出现意外错误。我正在android上运行。请帮我。
它应该显示音乐列表,但会出现意外错误。我正在android上运行。请帮我。
答案 0 :(得分:1)
将itemCount: _songs.length
更改为itemCount: _songs?.length ?? 0
-有助于避免出现异常情况
答案 1 :(得分:0)
由于您正在执行异步操作,因此将花费一定的时间,因此在您的应用首次构建时,songs数组为null。尝试以空数组而不是空数组开始:List<Song> _songs = [];
,然后,当异步操作完成时,setState将使小部件重新生成并显示包含数据的数组。