提问者:小点点

未处理的异常:NosuchMethodError:调用方法“add user”时为null


我正在尝试连接一个Firestore数据库到一个简单的Flutter应用程序。为了测试连通性,我按照Flutter Firestore文档中的说明添加了一个用户(在我的例子中,每次在“Software”小部件中点击Inkwell时都应该执行)。

但是,我收到错误:“Unhandled Exception:NosuchMethodError:方法'add User'被调用于Null.”-即使我给它赋值。

我按照其他页面上的所有说明进行操作,但仍然无法修复问题。有人能帮我解决这个问题吗?如果你需要进一步的信息,请告诉我。

Database.Dart:

import 'package:firebase_core/firebase_core.dart';
import 'package:blitz_shortcuts/main.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {
          final String userID;
          DatabaseService(this.userID);
        
          final String fullName = 'XYZ';
        
          // Referenz auf die Firestore Collection herstellen:
        
          final CollectionReference userSoftwareName =
              FirebaseFirestore.instance.collection("userSoftwareName");
        
          Future<void> addUser() async {
            return await userSoftwareName
                .doc(userID)
                .update({"full_name": fullName}).then((value) => print("User Added"));
          }
        }

主省道:

    import 'package:flutter/material.dart';
    import 'package:blitz_shortcuts/quizpage.dart';
    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'database.dart';
    import 'dart:convert';
    import 'dart:math';
    import 'dart:async';
    
    import 'package:flutter/services.dart';
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    
    // This is the software tile Widget
    
    String softwareName;
    DatabaseService database;
    
    void addUser() {
      database.addUser();
    }
    
    Widget software(
        BuildContext context, String softwareName, String softwareIcon) {
      return Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            children: [
              Padding(
                padding: EdgeInsets.all(10.0),
                child: InkWell(
                    onTap: () {
                      addUser();
                      Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                getjson(softwareName: softwareName),
                          ));
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(softwareIcon),
                        Text(
                          softwareName,
                          style: (TextStyle(
                            height: 2.0,
                            color: Colors.grey[600],
                            fontFamily: "RobotoCondensed",
                            fontSize: 14,
                          )),
                        )
                      ],
                    )),
              ),
            ],
          ));

}

// This creates a new row for a software category, e.g. Microsoft Office
Widget customrow(BuildContext context, String categoryName) {
  return Padding(
      padding: EdgeInsets.all(10),
      child: Column(children: [
        Stack(children: [
          Divider(
            color: Color.fromRGBO(3, 218, 198, 1),
            thickness: 2,
            indent: 120,
          ),
          Container(
            child: Text(
              categoryName,
              style: TextStyle(
                fontFamily: "Poppins",
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ]),
      ]));
}

/// This is the main class 

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  User user;
  DatabaseService database;

  /// Firebase connection:

  void connectToFirebase() async {
    final FirebaseAuth authenticate = FirebaseAuth.instance;
    UserCredential result = await authenticate.signInAnonymously();
    user = result.user;

    database = DatabaseService(user.uid);
  }

  // methods that are called on start of the App:

  @override
  void initState() {
    super.initState();
    Firebase.initializeApp().whenComplete(() {
      connectToFirebase();
      setState(() {});
    });
      }

// followed by the actual app... 

共1个答案

匿名用户

默认情况下,在dart文件中,如果您没有初始化任何内容,则所有变量和对象都为null。您必须创建一个像DatabaseService database=new DatabaseService();这样的对象,因为数据库在默认情况下是空的,因为您没有初始化它。

如果你不想一次又一次地制造对象,你也可以使用singleton。

谢了。