0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】The method 'add' was called on null(エラー対処法 )

Posted at

発生したエラー

NoSuchMethodError (
  NoSuchMethodError: The method 'add' was called on null. 
  Receiver: null

前提条件

  • Flutter 1.26.0-17.3.pre
  • Dart 2.12.0 (build 2.12.0-259.8.beta)

問題のコード

soundsLists.add(soundsList);
で要素をaddするときに該当のエラーが出ました。

class SoundsRepository {
  fetchSoundsRepository() async {
    final List<String> _requestSoundsUrls = [
      'assets/json/soundBox.json',
      'assets/json/audioList.json'
    ];

    List<List<Sounds>> soundsLists;
    _requestSoundsUrls.forEach((urls) async {
      final String _soundsResponse =
          await SoundsApiProvider().fetchSoundsApi(urls);

      if (_soundsResponse != "") {
        Map jsonArray = json.decode(_soundsResponse);

        // http通信ではなくて、ローカルからファイル取得
        List<Map<String, dynamic>> jsonAudioList =
            new List<Map<String, dynamic>>.from(jsonArray['audioList']);

        List<Sounds> soundsList =
            jsonAudioList.map((i) => new Sounds.fromJson(i)).toList();
        soundsLists.add(soundsList);
      } else {
        throw Exception("ERROR");
      }
    });

    return soundsLists;
  }

修正方法

BEFORE:

List<List<Sounds>> soundsLists;


AFTER:

List<List<Sounds>> soundsLists = List<List<Sounds>>();

原因

soundsListsがInitializeしていないのが原因。
dartだと上記のようにInitializeしないといけないらしい。

日々勉強

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?