简体   繁体   English

未处理的异常:NoSuchMethodError:在 null 上调用了方法“addUser”

[英]Unhandled Exception: NoSuchMethodError: The method 'addUser' was called on null

I am trying to connect a Firestore database to a simple Flutter app.我正在尝试将 Firestore 数据库连接到一个简单的 Flutter 应用程序。 To test the connectivity I followed the instructions in the Flutter Firestoredocumentation for adding a user (in my case, it should execute every time when tapping on an Inkwell in the "software" Widget).为了测试连接性,我按照 Flutter Firestore文档中的说明添加用户(在我的情况下,它应该在每次点击“软件”小部件中的 Inkwell 时执行)。

However, I receive the Error: "Unhandled Exception: NoSuchMethodError: The method 'addUser' was called on null."但是,我收到错误:“未处理的异常:NoSuchMethodError:方法‘addUser’被调用为空。” - Even if i assign a value to it. - 即使我给它赋值。

I followed all instructions on other pages but still couldn't fix the problem.我遵循了其他页面上的所有说明,但仍然无法解决问题。 Can anyone help with that issue?任何人都可以帮助解决这个问题吗? Please let me know if you need further information.如果您需要更多信息,请告诉我。

database.dart:数据库.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"));
          }
        }

main dart:主要飞镖:

    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... 

In the dart by default, all variables and objects are null if you are not initializing to that anything.默认情况下,在dart ,如果您没有初始化任何东西,所有变量和对象都是空的。 you have to create an object like DatabaseService database= new DatabaseService();您必须创建一个对象,如DatabaseService database= new DatabaseService(); because the database is null by default because you are not initializing it.因为数据库默认为空,因为您没有初始化它。

you can use singleton as well if you don't want to make the object again and again.如果您不想一次又一次地创建对象,也可以使用单例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的异常:NoSuchMethodError:在 null 上调用了方法“toRawHandle” - Unhandled Exception: NoSuchMethodError: The method 'toRawHandle' was called on null 未处理的异常:NoSuchMethodError:在 null 上调用了方法“insertData” - Unhandled Exception: NoSuchMethodError: The method 'insertData' was called on null [Flutter] 未处理的异常:NoSuchMethodError:方法 &#39;[]&#39; 在 null 上被调用 - [Flutter ]Unhandled Exception: NoSuchMethodError: The method '[]' was called on null Flutter:“未处理的异常:NoSuchMethodError:getter &#39;httpClientAdapter&#39; 在 null 上被调用。” - Flutter: "Unhandled Exception: NoSuchMethodError: The getter 'httpClientAdapter' was called on null." Flutter 提供程序错误:未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'owner' - Flutter Provider Error : Unhandled Exception: NoSuchMethodError: The getter 'owner' was called on null NoSuchMethodError:在 null 上调用了方法“&gt;” - NoSuchMethodError: The method '>' was called on null NoSuchMethodError 。 在 null 上调用了 getPosts 方法 - NoSuchMethodError . The method getPosts was called on null NoSuchMethodError: 在 null 上调用了方法“validate” - NoSuchMethodError: The method 'validate' was called on null NoSuchMethodError:在 null 上调用了方法“[]”。接收方:null - NoSuchMethodError: The method '[]' was called on null. Receiver: null NoSuchMethodError:在 null 上调用了方法“[]”| 解析 JSON - NoSuchMethodError: The method '[ ]' was called on null | Parsing a JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM