FLutter : User Provider return Null

Viewed 18

I'm beginner on Flutter ,My User Provider always return null. Details: on the file Add-article.dart . the circular widget always return null when i'm trying to display the image , while checking , i found that my userProvider is null. this is a school project , the deadline is 31/09 . if there is someone could help me i will be grateful

Coding Part

My User Provider

import 'package:flutter/material.dart';
import 'package:smartmedia/models/user.dart';
import 'package:smartmedia/ressources/auth_method.dart';

class UserProvider with ChangeNotifier{
    User? _user;
  final AuthMethods _authMethods = AuthMethods();
  User? get getUser=>_user;

  Future<void> refresh() async{
    User user = await _authMethods.getUserDetails();
    _user=user;
    print(_user);
    notifyListeners();
  }

}

My Main Class

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:smartmedia/providers/user_provider.dart';
import 'package:smartmedia/responsive/mobilescreen_layout.dart';
import 'package:smartmedia/responsive/responsive_layout_screen.dart';
import 'package:smartmedia/responsive/webscreen_layout.dart';
import 'package:smartmedia/screens/login_screen.dart';
import 'package:smartmedia/screens/subscreens/add_article_layout.dart';
import 'package:smartmedia/utils/colors.dart';

void main() async {
//ensure that flutter is being initialized
WidgetsFlutterBinding.ensureInitialized();
//wait for Firebase Initiliazing 
//if the Ki is a web application
if(kIsWeb){
await Firebase.initializeApp(
 options: const  FirebaseOptions('here i'm using the informations needed ')
) ;
}
//if it's mobile device
else{
await Firebase.initializeApp();
}

runApp(const Home());
}

class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {

return   MultiProvider(
 
 providers: [
   ChangeNotifierProvider(create: (_)=>UserProvider(),)
 ],
 child: MaterialApp(
 debugShowCheckedModeBanner: false,
     routes: {
       '/journalist/addArticle':(context)=>  AddArticleLayout()
     },
   color: white,
  title: 'Demo Smart Media Application',
   theme: ThemeData(primarySwatch: Colors.deepPurple,
   selectedRowColor: Colors.white,
   textTheme: Theme.of(context).textTheme.apply(
   
   bodyColor: Colors.black,
   displayColor: Colors.pinkAccent
   ),
   ),
   home:
   //  ResponsiveLayout(WebScreenLayout: WebScreen(), mobileScreenLayout: MobileScreen()),
   StreamBuilder(
     //work only if user sign in or sign out
     stream:FirebaseAuth.instance.authStateChanges() ,
     builder: ((context, snapshot) {
       if(snapshot.connectionState == ConnectionState.active)
       {
         if(snapshot.hasData){
           
           return const ResponsiveLayout(WebScreenLayout: WebScreen(), mobileScreenLayout: MobileScreenLayout());
         } else if(snapshot.hasError){
           return Center(child: Text('${snapshot.error}')
           );
         }
       }
       if(snapshot.connectionState == ConnectionState.waiting){

         return  const Center(
           child: CircularProgressIndicator(
             color: primaryColor,

           ) ,
         );
       }
       return const  LoginScreen();
     }
     
     
     ),
   ),

 ),
);


}}

And finaly this is the part where i want to display the Image


import 'dart:typed_data';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:smartmedia/models/user.dart'as Model;
import 'package:smartmedia/providers/user_provider.dart';
import 'package:smartmedia/utils/colors.dart';
import 'package:smartmedia/utils/utils.dart';

class AddArticleLayout extends StatefulWidget {

  
  const AddArticleLayout({Key? key}) : super(key: key);


  @override
  State<AddArticleLayout> createState() => _AddArticleLayoutState();
}
 
class _AddArticleLayoutState extends State<AddArticleLayout> {
    Uint8List? _file;

  _selectImage(BuildContext context) async{
    return showDialog(context: context, builder: (context){
      print("(----------------------------------------)");
      

    return  SimpleDialog(
      contentPadding: EdgeInsets.all(5),
      title: Text("اضافه منشور",style: TextStyle(fontSize: 15,color: primaryColor), textDirection: TextDirection.rtl,)  ,
      children: [
        SimpleDialogOption(
            padding:const EdgeInsets.all(20),
            child: const Text('أخد صوره من الكاميرة',textDirection: TextDirection.rtl,),
            onPressed: () async {
               
             Uint8List file = await pickImage(ImageSource.camera);
          

setState(() {
  _file=file;

 
});


            },

        ),
         SimpleDialogOption(
            padding:const EdgeInsets.all(20),
            child: const Text('اختيار صوره ',textDirection: TextDirection.rtl),
            onPressed: () async {
               
             Uint8List file = await pickImage(ImageSource.gallery);
setState(() {
  _file=file;
});

            },

        )
      ],
    );
    } );

  }
  @override
  Widget build(BuildContext context) {

        final User user = Provider.of<UserProvider>(context).getUser as User ;

      

    
    print("----------------------------------------------------------");
    print(user);
     
      // final int nom= context.read<int>() ;

      // print(nom);
return  Scaffold(
      backgroundColor: secondColor,
      appBar: AppBar
      (
       title: Text('اضافه صوره/فيديو',style: TextStyle(color: white,fontSize: 18),), 
       centerTitle: true,
        backgroundColor: secondColor,leading: IconButton(icon: const Icon(Icons.arrow_back),
      color: white,
      onPressed: (){Navigator.pop(context);},
      
      ),),
      body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
             SizedBox(
             
              child: CircleAvatar(
                 backgroundImage: NetworkImage((user.photoURL).toString()),
              ),
            ),SizedBox(width: MediaQuery.of(context).size.width*0.4,
            child: const TextField(
              style: TextStyle(color:Colors.red),
              
              textDirection: TextDirection.rtl,
              decoration: InputDecoration(hintText: " ...تعليق عن المحتوى",hintStyle: TextStyle(color: white),
              hintTextDirection: TextDirection.rtl,
              
              labelStyle: TextStyle(color: white),
               hoverColor: white,
              border: InputBorder.none,

            ),
            maxLines: 8,
            )
          ),
          SizedBox(height: 45,width: 45,child: AspectRatio(aspectRatio: 487/451,
          child: _file != null ? Image.memory(_file!) :
           Image.network("https://img.freepik.com/free-photo/gray-abstract-wireframe-technology-background_53876-101941.jpg?w=2000")
          )
          ),
          
          
           Column(
          
           children: [
             Center(
              child: IconButton(icon: const Icon(Icons.upload_rounded,color: Colors.blue,),
              onPressed: (() => _selectImage(context)),
              
              
              ),
             ),
           ],
           )      
          ],
          ),
        ],
      ),
       
    )
    ;
    
  }
}
0 Answers
Related