NoSuchMethodError:方法“ []”在null上被调用

时间:2019-09-17 07:52:27

标签: flutter google-cloud-firestore consumer flutter-provider

我遇到以下错误:

在构建StreamBuilder时引发了以下NoSuchMethodError(脏,状态:_StreamBuilderBaseState>#12214): 方法'[]'在null上被调用。 接收者:null 尝试致电:

由用户创建的导致错误的小部件的祖先是: 消费者

出于某种原因,这是在实现提供者和使用者之后发生的,但是我认为我的实现没有问题。 (应用程序在没有提供者和使用者的情况下运行良好)。我的Firestore数据库看起来像这样screenshot

我张贴了我的main.dart代码的图片,有没有提供者和消费者。 (无需调用它们,代码即可正常运行。)

带有消费者/提供者的Main.dart:

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();
          }
    });
    });
  }



  Widget rowCell(String count, String type) => new Expanded(
      child: new Column(
        children: <Widget>[
          new Text(
            '$count',
            style: new TextStyle(color: Colors.white),
          ),
          new Text(type,
              style: new TextStyle(
                  color: Colors.white, fontWeight: FontWeight.normal))
        ],
      ));
}

没有使用者/提供者的main.dart:

    void main() => runApp(new 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;
    //    final String imgUrl =
    //        'https://pixel.nymag.com/imgs/daily/selectall/2017/12/26/26-eric-schmidt.w700.h700.jpg';
    //      final String userId;
        return StreamBuilder<DocumentSnapshot>(
            stream: Firestore.instance
                .collection('users')
                .document('testuser')
                .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();
              }
            });
      }

      Widget rowCell(String count, String type) => new Expanded(
              child: new Column(
            children: <Widget>[
              new Text(
                '$count',
                style: new TextStyle(color: Colors.white),
              ),
              new Text(type,
                  style: new TextStyle(
                      color: Colors.white, fontWeight: FontWeight.normal))
            ],
          ));
    }

user_model.dart类:

class UserModel extends ChangeNotifier {

  String uid = 'testuser';
}

0 个答案:

没有答案