0

我正在用新版本从旧版本中学习颤振。所以,我多次遇到空值安全问题。

我在database.dart文件中有这样的代码:

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {
  final String uid;
  DatabaseService({required this.uid});
}

当我添加“必需”时它可以工作并且没有出现错误,但是我不能在文件中使用 DatabaseService()参数:home.dart

class Home extends StatelessWidget {
  Home({Key? key}) : super(key: key);

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return StreamProvider<QuerySnapshot?>.value(
      initialData: null,
      value: DatabaseService().brews,
      child: Scaffold(),
  }
}

错误home.dart

The named parameter 'uid' is required, but there's no corresponding argument.
Try adding the required argument.

而且,如果我不添加requiredDatabaseService({this.uid})那么错误将出现在database.dart

The parameter 'uid' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.

那么我如何DatabaseService()在其他文件中使用?

4

2 回答 2

1

如果不需要 uid,则使用空安全运算符

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseService {
  final String? uid;
  DatabaseService({this.uid});
}
于 2021-11-09T09:05:17.803 回答
0

在 nullsafety 中,有 2 种类型称为 non-null 和 nullable

  • 非空是您的变量不能为空的地方,因此您必须为其赋值
  • Nullable 是您的变量可以为空的地方,它可以在没有任何值的情况下运行(基本上它不需要任何值)

在你的情况下,你可以尝试使用这个'?使其可以为空的符号

像这样 :

class DatabaseService {
  final String? uid;
  DatabaseService({this.uid});
}

而且你不需要在它前面加上 required ,因为它允许为空

希望对您有所帮助!,对不起我的错误解释

于 2021-11-09T09:07:22.870 回答