0

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();

  @override
  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 ?

2 Answers 2

1

Use null safety operator if uid is not required

import 'package:cloud_firestore/cloud_firestore.dart';

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

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;
  DatabaseService({this.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

2
  • so, what is the difference between (?) <Question Mark> and (!) <Exclamation Mark> in null safety?
    – DVCone
    Nov 9, 2021 at 13:24
  • 1
    if you mean when you call nullable variable and you place (?) your statement has to be non mandatory, but if you can actually make sure that your nullable variable is free from null you can use the (!) because if you call it but its value is null, there will be error appear on your screen, basically the (!) mark is for make sure that your nullable variable contains value Nov 10, 2021 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.