The method '[ ]' was called on null

James Roth picture James Roth · Sep 16, 2019 · Viewed 10.5k times · Source

firestore setupI am running my app and getting the error:

"NoSuchMethodError: The Method '[ ]' was called on null. Receiver: null. Tried calling: ."

This is also happening for "photourl" and "total questions", all three fields that I have in my firestore database.

This error is occurring after I implemented provider, so I am not sure if this is a result of this.

My code is below:

void main() {
  runApp(
      ChangeNotifierProvider(
      builder: (context) => UserModel(),
      child: MyApp(),
      ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Profile Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Profile'),
    );
  }
}

class User {
  final int name;
  final DocumentReference reference;

  User.fromMap(Map<String, dynamic> map, {this.reference})
      : name = map['name'];

  User.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);
}

class Photo {
  final int photourl;
  final DocumentReference reference;

  Photo.fromMap(Map<String, dynamic> map, {this.reference})
      : photourl = map['photourl'];

  Photo.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);
}

class Questions {
  final int totalquestions;
  final DocumentReference reference;

  Questions.fromMap(Map<String, dynamic> map, {this.reference})
      : totalquestions = map['totalquestions'];

  Questions.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width;
    final _height = MediaQuery.of(context).size.height;
    return Consumer<UserModel>(builder: (context, userModel, child) {
      return StreamBuilder<DocumentSnapshot>(
        stream: Firestore.instance.collection(userModel.uid)
            .document(userModel.uid).snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Stack(
              children: <Widget>[
                new Container(
                  color: Colors.blue,
                ),
                new Image.network(
                  snapshot.data['photourl'].toString(),
                  fit: BoxFit.fill,
                ),
                new BackdropFilter(
                    filter: new ui.ImageFilter.blur(
                      sigmaX: 6.0,
                      sigmaY: 6.0,
                    ),
                    child: new Container(
                      decoration: BoxDecoration(
                        color: Colors.blue.withOpacity(0.9),
                        borderRadius: BorderRadius.all(Radius.circular(50.0)),
                      ),
                    )),
                new Scaffold(
                  appBar: new AppBar(
                    title: new Text(widget.title),
                    centerTitle: false,
                    elevation: 0.0,
                    backgroundColor: Colors.transparent,
                  ),
                  drawer: new Drawer(
                    child: new Container(),
                  ),
                  backgroundColor: Colors.transparent,
                  body: new Center(
                    child: new Column(
                      children: <Widget>[
                        new SizedBox(
                          height: _height / 12,
                        ),
                        new CircleAvatar(
                          radius: _width < _height ? _width / 4 : _height / 4,
                          backgroundImage: NetworkImage(snapshot.data['photourl']),
                        ),
                        new SizedBox(
                          height: _height / 25.0,
                        ),
                        new Text(
                          snapshot.data['name'],
                          style: new TextStyle(fontWeight: FontWeight.bold, fontSize: _width / 15, color: Colors.white),
                        ),
                        new Padding(
                          padding: new EdgeInsets.only(top: _height / 30, left: _width / 8, right: _width / 8),
                        ),
                        new Divider(
                          height: _height / 15,
                          color: Colors.white,
                        ),
                        new Row(
                          children: <Widget>[
                            rowCell(snapshot.data['totalquestions'], 'Answers'),
                            rowCell('£ ${int.parse(snapshot.data['totalquestions']) * 2}', 'Earned'),
                          ],
                        ),
                        new Divider(height: _height / 15, color: Colors.white),
                      ],
                    ),
                  ),
                ),
              ],
            );
          } else {
            return CircularProgressIndicator();
          }
        },
      );
    });
  }

Answer

Kushagra Saxena picture Kushagra Saxena · Sep 16, 2019

The error simply states that the operator [] is called on a variable that does not contain a Map object and is rather null. I would suggest you to place a check for null or provide a default value for map using ?? everytime before you access a property of map.