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

Issue

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 ?

Solution

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

Answered By – Kisame Hoshigaki

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *