-1

I'm working on a project( mobile app) with flutter and firebase and faced this error when i run the app:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel., null, null)
#0      FirebaseCoreHostApi.initializeCore (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:203:7)
<asynchronous suspension>
#1      MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:29:44)
<asynchronous suspension>
#2      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:7)
<asynchronous suspension>
#3      Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:31)
<asynchronous suspension>
#4      main (package:dachsmate/main.dart:14:3)
<asynchronous suspension>

N.B: there are no errors in the code .

This is the main :

import 'package:dachsmate/screen/auth_screen.dart';
import 'package:dachsmate/screen/intro_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:dachsmate/screen/forgotpass_screen.dart';
import 'package:dachsmate/screen/verifcode_screen.dart';
import 'package:dachsmate/screen/newpass_screen.dart';
import 'package:dachsmate/screen/userinterface_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var colors;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'flutter dachsmate',
      theme: ThemeData(
        primaryColor: Color(0x2B3B61FF),
        textTheme: TextTheme(
          headline1: TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.bold),
          headline2: TextStyle(fontSize: 30, color: Colors.yellow, fontWeight: FontWeight.bold),
          headline3: TextStyle(fontSize: 30, color: Colors.yellow, fontWeight: FontWeight.bold),
        ),
        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: Color(0x94FFFFFF),
          enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.blueGrey.withOpacity(0.01)),
              borderRadius: BorderRadius.circular(15)
          ),
          disabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.blueGrey.withOpacity(0.01)),
              borderRadius: BorderRadius.circular(15)
          ),
          focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.blueGrey.withOpacity(0.01)),
              borderRadius: BorderRadius.circular(15)
          ),
        ),
      ),
      home: IntroScreen(),
      routes: {
        'login': (context) => Authscreen(authType: AuthType.login),
        'register': (context) => Authscreen(authType: AuthType.register),
        'forgotpass': (context) => ForgotPassScreen(),
        'verifcode': (context) => VerifCodeScreen(),
        'newpass' : (context) => NewpassScreen(),
        'ui' : (context) => UserinterfaceScreen(),
      },
    );
  }
}

and this is the authentification form :

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dachsmate/widgets/original_button.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:dachsmate/screen/auth_screen.dart';
import 'package:dachsmate/screen/userinterface_screen.dart';
import 'package:firebase_storage/firebase_storage.dart' as fStorage;
import 'package:shared_preferences/shared_preferences.dart';

class AuthForm extends StatefulWidget {
  final AuthType authType;

  const AuthForm({Key? key, required this.authType}) : super(key: key);





  @override
  State<AuthForm> createState() => _AuthFormState();
}

class _AuthFormState extends State<AuthForm> {
  bool _isRegister = false;
  final _formkey = GlobalKey<FormState>();
  String _email = '', _password = '', _name ='';
  String _matricule = '';
  String _vidangeCode = '';
  TextEditingController anyController = TextEditingController();
  TextEditingController EmailController = TextEditingController();
  TextEditingController PasswordController = TextEditingController();
  TextEditingController NameController = TextEditingController();
  TextEditingController MatriculeController = TextEditingController();
  TextEditingController CodeController = TextEditingController();




  @override
  void initState() {
    super.initState();
    _isRegister = widget.authType == AuthType.register;
  }

  // Future<void> formValidation()async
  // {if }
  void authenticateUserSignUp() async {
    User? currentUser;
    final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    await firebaseAuth.createUserWithEmailAndPassword(
      email: EmailController.text.trim(),
      password: PasswordController.text.trim(),


    ).then((auth) {
      currentUser = auth.user;
    });
    if (currentUser != null) {
      saveDataToFirestore(currentUser!).then((value) {
        Navigator.pop (context);
        //send user to homePage
        Route newRoute = MaterialPageRoute(builder: (c) =>UserinterfaceScreen() );
        Navigator.pushReplacement(context, newRoute);

      });
    }
  }


  Future saveDataToFirestore (User currentUser) async
  {
    FirebaseFirestore.instance.collection("users").doc(currentUser.uid).set({
      "userUID":currentUser.uid,
      "userEmail":currentUser.email,
      "userName":NameController.text.trim(),
      "userMatricule":MatriculeController.text.trim(),
      "userCode":CodeController.text.trim(),
      "status": "approved",
      // "lat": position!.latitude,
      // "lng": position!.longitude,
    });
    //SAve data locally
    authenticateUserSignUp();
    SharedPreferences? sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.setString("uid", currentUser.uid);
    await sharedPreferences.setString("name", NameController.text.trim());
    await sharedPreferences.setString("email", currentUser.email.toString());
    await sharedPreferences.setString("password", PasswordController.text.trim());
    await sharedPreferences.setString("Matricule", MatriculeController.text.trim());
    await sharedPreferences.setString("code", CodeController.text.trim());
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formkey,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            if (_isRegister) SizedBox(height: 16),
            if (_isRegister)
              TextFormField(
                onChanged: (value) => _name = value,
                validator: (value) =>
                value!.isEmpty ? 'Entrer un nom et un prénom' : null,
                decoration: InputDecoration(
                  labelText: 'Entrer votre nom et prénom',
                  hintText: 'exp: Jean Dubois',
                  filled: true,
                  fillColor: Colors.white.withOpacity(0.3),
                  labelStyle: TextStyle(color: Colors.black54),

                ),
              ),
            SizedBox(height: 13),
            TextFormField(
              onChanged: (value) => _email = value,
              validator: (value) =>
              value!.isEmpty ? 'Entrer un mail valide' : null,
              decoration: InputDecoration(
                labelText: 'Entrer votre adresse mail',
                hintText: 'exp: exemple@gmail.com',
                filled: true,
                fillColor: Colors.white.withOpacity(0.3),
                labelStyle: TextStyle(color: Colors.black54),
              ),
            ),
            SizedBox(height: 16),
            TextFormField(
              onChanged: (value) => _password = value,
              validator: (value) => value!.length < 8
                  ? 'Votre mot de passe doit comporter au moins 8 caractères'
                  : null,
              decoration: InputDecoration(
                labelText: 'Entrer votre mot de passe',
                filled: true,
                fillColor: Colors.white.withOpacity(0.3),
                labelStyle: TextStyle(color: Colors.black54),
              ),
              obscureText: true,
            ),
            if (_isRegister) SizedBox(height: 16),
            if (_isRegister)
              TextFormField(
                onChanged: (value) => _matricule = value,
                validator: (value) => value!.isEmpty ? 'Entrer un matricule valide' : null,
                decoration: InputDecoration(
                  labelText: 'Entrer votre matricule',
                  hintText: 'exp: 123 TUN 1234',
                  filled: true,
                  fillColor: Colors.white.withOpacity(0.3),
                  labelStyle: TextStyle(color: Colors.black54),
                ),
              ),
            if (_isRegister) SizedBox(height: 16),
            if (_isRegister)
              TextFormField(
                onChanged: (value) => _vidangeCode = value,
                validator: (value) => value!.isEmpty ? 'Entrer un code de vidange valide' : null,
                decoration: InputDecoration(
                  labelText: 'Entrer votre code de la carte de vidange',
                  hintText: 'exp: ABCD1234',
                  filled: true,
                  fillColor: Colors.white.withOpacity(0.3),
                  labelStyle: TextStyle(color: Colors.black54),
                ),
              ),
            SizedBox(height: 10),
            if (widget.authType == AuthType.login) // Render forgot password button only in login screen
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () {
                    Navigator.of(context).pushReplacementNamed('forgotpass');// Add code to handle forgot password button click
                  },
                  child: Text(
                    'Mot de passe oublié ?',
                    style: TextStyle(
                      color: Colors.white70,
                      fontSize: 12.5,
                    ),
                  ),
                ),
              ),
            SizedBox(height: 25),
            OriginalButton(
              text: widget.authType == AuthType.login
                  ? 'Connexion'
                  : 'Créer un compte',
              onPressed: () {
                if (_formkey.currentState!.validate()) {
                  // print(_name);
                  // print(_email);
                  // print(_password);
                  Navigator.of(context).pushNamed('ui');
                }
              },

              textColor: Colors.black,
              bgColor: Color(0xFFFFD803),
            ),
            SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  onPressed: () {
                    if (widget.authType == AuthType.login)
                      Navigator.of(context).pushReplacementNamed('register');
                    else
                      Navigator.of(context).pushReplacementNamed('login');
                  },
                  child: Text(
                    widget.authType == AuthType.login
                        ? 'Première fois ? Inscrivez-vous'
                        : 'Vous avez un compte ? Connectez-vous',
                    style: TextStyle(
                      color: Colors.white70,
                      fontSize: 14.5,
                    ),
                  ),
                ),
              ],
            ),

          ],
        ),
      ),
    );
  }
}

(i was expecting the app to work and when i enter any data in sign up for example it is stored in the firebase .)

1 Answers1

1

If you are using these dependecies then replace it with a latest version:

  • firebase_messaging
  • firebase_core
  • flutter_local_notifications

Then in android/app/build.gradle update compileSdkVersion flutter.compileSdkVersion to 33.

This exception could also be thrown if you are running your app on windows or Mac, running it on Ios or android will solve the problem

if this still didn't fix your problem try this answer

mishalhaneef
  • 672
  • 8
  • 29