Home > Back-end >  Learning Flutter/Dart....I can't figure out why I am getting these errors
Learning Flutter/Dart....I can't figure out why I am getting these errors

Time:03-29

I can't figure out why I am getting the following 2 errors:

  1. The argument type 'User?' can't be assigned to the parameter type 'User'.

  2. Undefined name '_signInAnonymously'.Try correcting the name to one that is defined, or defining the name.

I am using the most recent Flutter 2.10.3

class SignInPage extends StatelessWidget {
  const SignInPage({Key? key, required this.onSignIn}) : super(key: key);
  final void Function(User) onSignIn;
  
  Future<void> _signInAnonymously() async {
    try {
      final userCredentials = await FirebaseAuth.instance.signInAnonymously();
      // ignore: unnecessary_string_interpolations
      onSignIn(userCredentials.user);
    } catch (e) {
      print(e.toString());
    }
  }
  
}

Widget _buildContent() {
  return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          SignInButton(
            text: 'Sign In Anonymously',
            textColor: Colors.black,
            color: Colors.white,
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
              Radius.circular(16),
            )),
            onPressed: _signInAnonymously,
          ),
        ],
      ));
}

CodePudding user response:

Problem #1

The type User? is telling dart that User is nullable, it can be either User or null. A nullable type cannot be assigned to a non-nullable type, since a non-nullable type cannot have null as value. Therefore, you should either change User to nullable:

final void Function(User?) onSignIn;

Or make sure that User is not null before assigning it.

Problem #2

Your _buildContent is outside of SignInPage. _signInAnonymously is contained inside SignInPage, so it cannot be accessed from _buildContent.

You should place _buildContent inside SignInPage or make _signInAnonymously accessible in a shared scope.

CodePudding user response:

user and user? are different try adding a ? user, see null safety.

User? can be null and User cannot.

  • Related