Irfan Ganatra
Irfan Ganatra

Reputation: 1346

not getting error while changing value of final in flutter..it should generate error

I have noticed one thing in a tutorial that it changes the value of final object and working well, but so far I know , final can't be changed...

Than why it is working well with this code..

here is the code

check my commented lines

class CompleteProfile extends StatefulWidget {
  final UserModel userModel;
  final User firebaseUser;

  const CompleteProfile({Key? key, required this.userModel, required this.firebaseUser}) : super(key: key);

  @override
  _CompleteProfileState createState() => _CompleteProfileState();
}

class _CompleteProfileState extends State<CompleteProfile> {

  File? imageFile;
  TextEditingController fullNameController = TextEditingController();

void uploadData() async {

    UIHelper.showLoadingDialog(context, "Uploading image..");

    UploadTask uploadTask = FirebaseStorage.instance.ref("profilepictures").child(widget.userModel.uid.toString()).putFile(imageFile!);

    TaskSnapshot snapshot = await uploadTask;

    String? imageUrl = await snapshot.ref.getDownloadURL();
    String? fullname = fullNameController.text.trim();


// here are the statement of changing value of final object....
    widget.userModel.fullname = fullname;
    widget.userModel.profilepic = imageUrl;

    await FirebaseFirestore.instance.collection("users").doc(widget.userModel.uid).set(widget.userModel.toMap()).then((value) {
      log("Data uploaded!");
      Navigator.popUntil(context, (route) => route.isFirst);
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) {
          return HomePage(userModel: widget.userModel, firebaseUser: widget.firebaseUser);
        }),
      );
    });
  }

 @override
  Widget build(BuildContext context) {
    return Scaffold(
```

Upvotes: 0

Views: 38

Answers (1)

Han Parlak
Han Parlak

Reputation: 777

Are you sure your UserModel class's fields: fullname and profilepic is final? Currently, you're changing these fields, not the UserModel object (which is final). If they're not marked as final, it's only logical for them to be changed.

final keyword does not apply to complex objects' fields. They ought to be final too if you want them to never change their values.

If you want to see an error try:

widget.userModel = UserModel();

or make fields fullname and profilepic final:

class UserModel{
   final String? fullName;
   final String? profilepic;
}

then try:

widget.userModel.fullName = 'Anything' // this will raise an error

Upvotes: 1

Related Questions