Flutter: Error when trying to add data into a Map List

6,254

Solution 1

List<Map<String, String>> productMap;

should be

List<Map<String, String>> productMap = [];

otherwise productMap is only declared, but not initialized (null)

Solution 2

You have not initialised the List.

Please change

List<Map<String, String>> productMap;

to

List<Map<String, String>> productMap = <Map<String, String>>[];

Hope this helped!

Share:
6,254
PeakGen
Author by

PeakGen

CTO

Updated on December 09, 2022

Comments

  • PeakGen
    PeakGen over 1 year

    I am very much new to Flutter. I am developing a testing app and blow is my code.

    main.dart

    import 'package:flutter/material.dart';
    
    import './pages/homepage.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return MaterialApp(
          theme: ThemeData(primaryColor: Colors.green),
          home: Homepage(),
        );
      }
    }
    

    homepage.dart

    import 'package:flutter/material.dart';
    
    class Homepage extends StatelessWidget {
      List<Map<String, String>> productMap;
    
      Homepage() {
        productMap.add({"title": "Chocolate", "imageUrl": ""});
      }
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
          appBar: AppBar(
            title: Text("Choco Factory"),
          ),
          body: HomepageUI(),
        );
      }
    }
    
    class HomepageUI extends StatefulWidget {
      HomepageUI() {}
    
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _HomepageUIBuilder();
      }
    }
    
    class _HomepageUIBuilder extends State<HomepageUI> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Expanded(
          child: Column(
            children: <Widget>[
              ListView.builder(
                itemBuilder: _listBuilder,
              )
            ],
          ),
        );
      }
    
      Widget _listBuilder(BuildContext context, int index) {
        return Card(
          child: Column(
            children: <Widget>[
              Image.asset("name"),
              Text("data"),
              RaisedButton(
                onPressed: () {},
                child: Text("Details"),
                color: ThemeData().primaryColor,
              )
            ],
          ),
        );
      }
    }
    

    I get the following error and I can't figure out why. I am from Java background and the code seems OK to me. Also I have another question, in Java Map we can add many key-value pairs to the Map but in Flutter it seems only one key-value pair is possible?

    Launching lib\main.dart on A37f in debug mode...
    Built build\app\outputs\apk\debug\app-debug.apk.
    I/Choreographer(11935): Skipped 87 frames!  The application may be doing too much work on its main thread.
    I/flutter (11935): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
    I/flutter (11935): The following NoSuchMethodError was thrown building MyApp(dirty):
    I/flutter (11935): The method 'add' was called on null.
    I/flutter (11935): Receiver: null
    I/flutter (11935): Tried calling: add(_LinkedHashMap len:2)
    I/flutter (11935): When the exception was thrown, this was the stack:
    I/flutter (11935): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
    I/flutter (11935): #1      new Homepage 
    I/flutter (11935): #2      MyApp.build 
    I/flutter (11935): #3      StatelessElement.build 
    I/flutter (11935): #4      ComponentElement.performRebuild 
    I/flutter (11935): #5      Element.rebuild 
    I/flutter (11935): #6      ComponentElement._firstBuild 
    I/flutter (11935): #7      ComponentElement.mount 
    I/flutter (11935): #8      Element.inflateWidget 
    I/flutter (11935): #9      Element.updateChild 
    I/flutter (11935): #10     RenderObjectToWidgetElement._rebuild 
    I/flutter (11935): #11     RenderObjectToWidgetElement.mount 
    I/flutter (11935): #12     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> 
    I/flutter (11935): #13     BuildOwner.buildScope 
    I/flutter (11935): #14     RenderObjectToWidgetAdapter.attachToRenderTree 
    I/flutter (11935): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.attachRootWidget 
    I/flutter (11935): #16     runApp 
    I/flutter (11935): #17     main 
    I/flutter (11935): #18     _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
    I/flutter (11935): #23     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
    I/flutter (11935): #24     _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
    I/flutter (11935): #25     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
    I/flutter (11935): (elided 4 frames from package dart:async)
    I/flutter (11935): ════════════════════════════════════════════════════════════════════════════════════════════════════