Search code examples
firebaseflutterdartprofileprovider

How to use provider correctly while I'm tryng to set a profile management?


I'm trying to use provider to get different informations about the user, (actually the uid) but it's not working because the .auth isn't defined for the type 'AuthClass', by the way I put AuthClass because my code is there but I'm not sure it's the good class. I looked for solutions and they say that we have to use our provider auth class but I don't know what is it either where I can find. Maybe you can help me

This is my code ( the .auth is underlined in red ):

body: SingleChildScrollView(
        child: Column(
          children: <Widget> [
            FutureBuilder(
              future: Provider.of<AuthClass>(context).auth.inputData(),
              builder: ( context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Text("${snapshot.data}");
                } else {
                  return Text("Loading...");
                }
              },
            )
          ]
        )
      )

And this is the other part of my code which contains inputData():

import 'package:firebase_auth/firebase_auth.dart';

class AuthClass {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  void inputData()  async {
    final User? user =  _auth.currentUser;
    final uid = user!.uid;
    print(uid);
  }
}


Solution

  • in order to use Provider, you should modify your code as follow:

    1. modify AuthClass:
    class AuthClass extends ChangeNotifier {
      final FirebaseAuth _auth = FirebaseAuth.instance;
    
      Future<bool> inputData()  async {
        final User? user =  await _auth.currentUser;
        final uid = user!.uid;
        print(uid);
        return true;
      }
    }
    
    1. use it:
    Provider.of<AuthClass>(context).inputData(), // .auth is redundant
    
    1. make sure you have defined the provider in your main file:
    ChangeNotifierProvider(
          create: (context) => AuthClass(),
          child: const MyApp(),
        ),
    

    also you should add Provider package to your dependency.