I'm trying to run the ambulance app in flutter and facing these errors

Issue

I’m facing this error in flutter application. Please help me in resolving the error

Launching lib\main.dart on SM J415F in debug mode…
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
lib/services/auth.dart:16:18: Error: The getter ‘onAuthStateChanged’ isn’t defined for the class ‘FirebaseAuth’.
– ‘FirebaseAuth’ is from ‘package:firebase_auth/firebase_auth.dart’
(‘../../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.2.0/lib/firebase_auth.dart’).
Try correcting the name to the name of an existing getter, or defining a getter or field named ‘onAuthStateChanged’.
return _auth.onAuthStateChanged
^^^^^^^^^^^^^^^^^^

lib/screens/authenticate/sign_in.dart:25:7: Error: No named parameter with the name 'resizeToAvoidBottomPadding'.
      resizeToAvoidBottomPadding: false,
      ^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/flutter/packages/flutter/lib/src/material/scaffold.dart:1451:9:

Context: Found this candidate, but the arguments don’t match.
const Scaffold({
^^^^^^^^

lib/screens/authenticate/register.dart:25:7: Error: No named parameter with the name 'resizeToAvoidBottomPadding'.
      resizeToAvoidBottomPadding: false,
      ^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/flutter/packages/flutter/lib/src/material/scaffold.dart:1451:9:

Context: Found this candidate, but the arguments don’t match.
const Scaffold({
^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\flutter\bin\flutter.bat'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org

BUILD FAILED in 3m 19s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

This is the code of file register.dart

import 'package:flutter/material.dart';
import 'package:my_app/services/auth.dart';
//import 'package:my_app/screens/authenticate/sign_in.dart';
//import 'package:my_app/screens/authenticate/authenticate.dart';
//import 'package:my_app/services/auth.dart';
//import 'package:email_validator/email_validator.dart';

class Register extends StatefulWidget {
  final Function toggleView;
  Register({this.toggleView});
  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();

  String email = '';
  String password = '';
  String error = '';
  bool isEmailValid = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      body: Container(
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
        child: Form(
            key: _formKey,
            child: Column(children: [
              SizedBox(height: 40),
              Text(
                "Welcome! \n\nCreate an new account",
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 30,
                    fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 20),
              TextFormField(
                decoration: InputDecoration(
                    hintText: 'Email',
                    fillColor: Colors.grey[300],
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 3)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.purple[900]))),
                validator: (value) => value.contains('@') && value.contains('.')
                    ? null
                    : 'Enter a valid email',
                onChanged: (val) {
                  setState(() {
                    email = val;
                  });
                },
              ),
              SizedBox(height: 20),
              TextFormField(
                decoration: InputDecoration(
                    hintText: 'Password',
                    fillColor: Colors.grey[300],
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 3)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.purple[900]))),
                validator: (val) =>
                    val.length < 6 ? 'Enter a password 6+ chars long' : null,
                obscureText: true,
                onChanged: (val) {
                  setState(() {
                    password = val;
                  });
                },
              ),
              SizedBox(height: 20),
              RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(color: Colors.purple[100])),
                  color: Colors.purple[300],
                  child: Text(
                    'Register',
                    style: TextStyle(color: Colors.white),
                  ),
                  onPressed: () async {
                    if (_formKey.currentState.validate()) {
                      try {
                        dynamic result = await _auth.registerWithEmailPassword(
                            email, password);
                      } catch (e) {
                        error = 'Please enter a valid email';
                      }
                    }
                  }),
              SizedBox(height: 20),
              RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(color: Colors.purple[100])),
                  color: Colors.purple[300],
                  child: Text('Sign in to an existing account',
                      style: TextStyle(color: Colors.white)),
                  onPressed: () async {
                    widget.toggleView();
                  }),
            ])),
      ),
    );
  }
}

This is the code of file sign_in.dart

import 'package:flutter/material.dart';
//import 'package:my_app/screens/authenticate/register.dart';
//import 'package:my_app/screens/home/home.dart';
import 'package:my_app/services/auth.dart';

class SignIn extends StatefulWidget {
  final Function toggleView;
  SignIn({this.toggleView});
  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {
  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();

  // text field states
  String email = '';
  String password = '';
  String error = '';

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Colors.white,
      body: Container(
        padding: EdgeInsets.symmetric(vertical: 20, horizontal: 50),
        child: Form(
            key: _formKey,
            child: Column(children: [
              SizedBox(height: 40),
              Text(
                "User Sign In \n",
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 30,
                    fontWeight: FontWeight.bold),
              ),
              TextFormField(
                decoration: InputDecoration(
                    hintText: 'Password',
                    fillColor: Colors.grey[300],
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 3)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.purple[900]))),
                validator: (value) => value.contains('@') && value.contains('.')
                    ? null
                    : 'Enter a valid email',
                onChanged: (val) {
                  setState(() {
                    email = val;
                  });
                },
              ),
              SizedBox(height: 20),
              TextFormField(
                decoration: InputDecoration(
                    hintText: 'Password',
                    fillColor: Colors.grey[300],
                    filled: true,
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 3)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.purple[900]))),
                validator: (val) =>
                    val.length < 6 ? 'Enter a password 6+ chars long' : null,
                obscureText: true,
                onChanged: (val) {
                  setState(() {
                    password = val;
                  });
                },
              ),
              SizedBox(height: 20),
              RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(color: Colors.purple[100])),
                  color: Colors.purple[300],
                  child: Text('Sign in', style: TextStyle(color: Colors.white)),
                  onPressed: () async {
                    if (_formKey.currentState.validate()) {
                      try {
                        dynamic result = await _auth.signInWithEmailPassword(
                            email, password);
                      } catch (e) {
                        error = 'Could not sign in with those credentials';
                        print(error);
                      }
                    }
                  }),
              SizedBox(height: 20),
              RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(color: Colors.purple[100])),
                  color: Colors.purple[300],
                  child: Text('Create a new account',
                      style: TextStyle(color: Colors.white)),
                  onPressed: () async {
                    widget.toggleView();
                  }),
              Text(error)
            ])),

        /*child: RaisedButton(
            child: Text("Sign in as a Guest"),
            onPressed: () async {
              dynamic result = await _auth.signInAnon();
              print(result);
              if (result == null) {
                print('Error Signing in');
              } else {
                print('Signed In');
                return Home();
              }
            }),*/
      ),
    );
    return scaffold;
  }
}

This is the code from file auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_app/models/user.dart';
//import 'package:my_app/screens/home/home.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // create user obj based on FirebaseUser
  TheUser _userFromFirebaseUser(User user) {
    return user != null ? TheUser(uid: user.uid) : null;
  }

  //auth change user stream
  Stream<TheUser> get user {
    // ignore: deprecated_member_use
    return _auth.onAuthStateChanged
        .map((User user) => _userFromFirebaseUser(user));
  }

  //Anonymous
  Future signInAnon() async {
    try {
      UserCredential result = await _auth.signInAnonymously();
      User user = result.user;
      return _userFromFirebaseUser(user);
      //return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  //sign iin Email and password
  Future signInWithEmailPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.signInWithEmailAndPassword(
          email: email.trim(), password: password);
      User user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  // register
  Future registerWithEmailPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(
          email: email.trim(), password: password);
      User user = result.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  //sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print('Error Occured: ' + e.toString());
      return null;
    }
  }
}

This is the code from file main.dart

import 'package:flutter/material.dart';
import 'package:my_app/screens/wrapper.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:my_app/services/auth.dart';
import 'package:provider/provider.dart';
import 'package:my_app/models/user.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<TheUser>.value(
        value: AuthService().user, child: MaterialApp(home: Wrapper()));
  }
}

Solution

2 things seem to be amiss here.

  1. You are using a deprecated parameter resizeToAvoidBottomPadding of the scaffold. Change it to resizeToAvoidBottomInset instead.

  2. You are using another deprecated api from Firebase which is FirebaseAuth.instance.onAuthStateChanged. You should now use it like this,

    _auth.authStateChanges().map((User user) => _userFromFirebaseUser(user));
    

Answered By – Nisanth Reddy

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

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