0

I'm working on create and join group using groupID project but after flutter migration when i user created group i got an error that currentUser returns null.

here is the trace error (to overcome it i used a condion as bellow it codes but was not solution)

Syncing files to device MO 01K...
I/flutter (15786): the user uid is Fts7cm617ShS79JxqGRUOdsz7zo2
Reloaded 1 of 2161 libraries in 3,199ms (compile: 176 ms, reload: 1313 ms, reassemble: 1238 ms).
I/flutter (15786): the user uid is Fts7cm617ShS79JxqGRUOdsz7zo2
I/flutter (15786): User is available!
E/flutter (15786): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'UserModel' in type cast
E/flutter (15786): #0      _OurAddBookState._addBook (package:jattendence/Admin/screens/addBook/addBook.dart:108:64)
E/flutter (15786): #1      _OurAddBookState.build.<anonymous closure> (package:jattendence/Admin/screens/addBook/addBook.dart:240:25)
E/flutter (15786): #2      _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
E/flutter (15786): #3      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)


here is may userModel class

import 'package:cloud_firestore/cloud_firestore.dart';


class UserModel {
  String? uid;
  String? email;
  Timestamp? accountCreated;
  String? fullName;
  String? groupId;
  String? notifToken;

  UserModel({
    this.uid,
    this.email,
    this.accountCreated,
    this.fullName,
    this.groupId,
    this.notifToken,
  });

  UserModel.fromDocumentSnapshot({required DocumentSnapshot <Map<String,dynamic>> doc}) {
 

    uid = doc.id;
    email = doc.data()?['email'];
    accountCreated = doc.data()?['accountCreated'];
    fullName = doc.data()?['fullName'];
    groupId = doc.data()?['groupId'];
    notifToken = doc.data()?['notifToken'];
  }

here there is where i call currentUser when user creating group

class OurAddBook extends StatefulWidget {
  final bool? onGroupCreation;
  final bool? onError;
  final String? groupName;
  final UserModel? currentUser;

  OurAddBook({
    this.onGroupCreation,
    this.onError,
    this.groupName,
    this.currentUser,
  });
  @override
  _OurAddBookState createState() => _OurAddBookState();
}

class _OurAddBookState extends State<OurAddBook> {
  final addBookKey = GlobalKey<ScaffoldState>();

  TextEditingController _bookNameController = TextEditingController();
  TextEditingController _authorController = TextEditingController();
  TextEditingController _lengthController = TextEditingController();

  DateTime _selectedDate = DateTime.now();

  initState() {
    super.initState();
    _selectedDate = DateTime(_selectedDate.year, _selectedDate.month,
        _selectedDate.day, _selectedDate.hour, 0, 0, 0, 0);
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime.now(),
        lastDate: DateTime(2222));

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = DateTime(picked.year, picked.month, picked.day,
            _selectedDate.hour, 0, 0, 0, 0);
      });
    }
  }

  Future _selectTime() async {
    await showDialog<int>(
      context: context,
      builder: (BuildContext context) {
        int _currentIntValue = 0;
        return NumberPicker(
          value: _currentIntValue,
          minValue: 0,
          maxValue: 23,
          //initialIntegerValue: 0,
          infiniteLoop: true, onChanged: (int value) {  },
          //value: null,
        );
      },
    ).then(( value) {
      if (value != null) {
        setState(() {
          _selectedDate = DateTime(_selectedDate.year, _selectedDate.month,
              _selectedDate.day, value, 0, 0, 0, 0);
        });
      }
    });
  }

  void _addBook(BuildContext context, String? groupName, BookModel? book) async {
    String _returnString;

    if (_selectedDate.isAfter(DateTime.now().add(Duration(days: 1)))) {

        if (widget.currentUser == null) {
          print('current user not available');
        } else {
          print('User is available!');
          if (widget.onGroupCreation!) {
            _returnString =
            await DBFuture().createGroup(
                groupName!, widget.currentUser?.getCurrentUser as UserModel, book!); // this is where i got error the condition can't be true because currentUser is null 

            //await DBFuture().createGroup(groupName!, widget.currentUser!, book!);
          } else if (widget.onError!) {
            _returnString =
            await DBFuture().addCurrentBook(
                widget.currentUser?.groupId as String, book!);
          } else {
            _returnString =
            await DBFuture().addNextBook(
                widget.currentUser?.groupId as String, book!);
          }

          if (_returnString == "success") {
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(
                  builder: (context) => OurRoot(),
                ),
                    (route) => false);
          }


i have tried many solutions given on stuckOverFlow(here)but nothings worked for my case like this Getting current user's data from firebase firestore in flutter and this Is there a way to get Firestore data to User model class in flutter then pass the data to the screens but the above solution was for old flutter version and for my case i just want currentUser details to be used in creating group(in group collection) as you see in codes above

and also i tried to refer to Migration to cloud_firestore 2.0.0 but i didn't get it.

i also tried to user FirebaseAuth but i was not the case.

please help me, thank you.

  • 1
    "i got an error that currentUser returns null" Please edit your question to include the exact error message you get, the stack trace for that message, and indicate which line in the code you shared the error comes from. – Frank van Puffelen Nov 09 '22 at 14:45
  • @FrankvanPuffelen i tried to edit the question please help me thank you – Nizeyimana Jc Nov 09 '22 at 15:35

1 Answers1

0

My guess it that the error comes from this code:

widget.currentUser?.getCurrentUser as UserModel

If so, your widget.currentUser?.getCurrentUser returns null, which (as the error says) can't be cast to a UserModel.

You'll need to decide what you want your app to when when getCurrentUser returns null and then implement that in your code.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • i understand but i want to return user info from class UserModel so i can create a group with those user info. that's where i stuck because i don't get how i can use UserModel and get current user information and store it in group collection during group creation. – Nizeyimana Jc Nov 09 '22 at 21:14