Adding elements to List in Flutter from For statement?

21,108

You are not instantiating your searchIds object. add this

List searchIds = new ArrayList<>();

(Or)

List searchIds = new List(); 
Share:
21,108

Related videos on Youtube

Charles Jr
Author by

Charles Jr

Jack of All Trades - Master of Few!! Started with Obj-C.then(Swift)!.now(Flutter/Dart)! Thank everyone for every answer, comment, edit, suggestion. Can't believe I've been able to answer a few myself :-)

Updated on April 26, 2020

Comments

  • Charles Jr
    Charles Jr almost 4 years

    I'm receiving the following error while trying to add elements from my for loop to my List...

    NoSuchMethodError: The method 'addAll' was called on null.
        Receiver: null
        Tried calling: addAll("LrWr826cd3Y")
    

    Here is my code...

    Future getData() async {
        //Map videoId;
    
        String url = 'https://Youtube API';
        var httpClient = createHttpClient();
        var response = await httpClient.read(url);
        Map data = JSON.decode(response);
        var videos = data['items']; //returns a List of Maps
    
        List searchTitles;
        List searchIds;
        List searchImages;
    
        for (var items in videos) {
          //iterate over the list
          Map myMap = items; //store each map
          final video = (myMap['id'] as Map);
          print(video['videoId']);
          searchIds.addAll(video['videoId']);
          final details = (myMap['snippet'] as Map);
          final videoimage = (details['thumbnails'] as Map);
          final medium = (videoimage['medium'] as Map);
    
        }
    
        setState(() { });
    
        if (!mounted) return;
      }
    

    print(video['videoId']); successfully lists the 3 Youtube video ids as Strings. searchIds.addAll(video['videoId']); throws the error. I've tried both searchIds.add and searchIds.addAll. Where am I going wrong?

    I would like to eventually push these lists to my List class here..

    class CardInfo {
      //Constructor
      List id;
      List title;
      List video;
    
      CardInfo.fromJson(List json) {
        this.id;
        this.title;
        this.video;
      }
    }
    
  • Charles Jr
    Charles Jr over 6 years
    This is how I got it to work for Flutter... List searchIds = new List();
  • milad zahedi
    milad zahedi over 6 years
    I see your problem is fixed. Good job.
  • Gowthaman M
    Gowthaman M almost 5 years
    List searchIds = new List(); this is worked for me.
  • poonam kalra
    poonam kalra almost 3 years
    You can also use List searchIds = [];