what is other solution for "required" in null safety to get uid in firestore?


Asked by DVCone on November 09, 2021 (source).

I'm learning flutter from the older version with the new one. so, I have many times problem with null safety.

I have code in database.dart file like this :

import 'package:cloud_firestore/cloud_firestore.dart';

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

it works and no error appeared when I add "required", but I can't use DatabaseService() parameter in home.dart file :

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

  final AuthService _auth = AuthService();

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

the error in home.dart is

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

and, if I don't add required in DatabaseService({this.uid}) then the error will appear in 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.

then how I can use DatabaseService() in other file ?


Question answered by Kisame H (source).

in nullsafety there is 2 type called non-null and nullable

  • Non-null is where your variable cannot be empty so you got to assign value to it
  • Nullable is where your variable can be empty, it able to run without any value (basically it doesn't require any value in it)

in your case you can try using this '?' symbol to make it nullable

just like this :

class DatabaseService {
  final String? uid;

and you don't need to put required in front of it, because it allowed to be empty

hope it helps!, sorry for my bad explanation