【问题标题】:Unhandled Exception: NoSuchMethodError: The method 'addUser' was called on null未处理的异常:NoSuchMethodError:在 null 上调用了方法“addUser”
【发布时间】:2021-01-04 12:51:57
【问题描述】:

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

但是,我收到错误消息:“未处理的异常:NoSuchMethodError:在 null 上调用了方法 'addUser'。” - 即使我给它赋值。

我按照其他页面上的所有说明进行操作,但仍然无法解决问题。任何人都可以帮助解决这个问题吗?如果您需要更多信息,请告诉我。

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

【问题讨论】:

    标签: android firebase flutter google-cloud-firestore


    【解决方案1】:

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

    如果您不想一次又一次地制作对象,也可以使用单例。

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2020-01-11
      • 2021-02-11
      • 2021-06-10
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2022-11-17
      相关资源
      最近更新 更多