How to display the assigned card to only specific user in flutter - firebase

I am creating a system that only certain user can see the list of the projects. The list of the projects will be shown in user application when the projects have been assigned to them thru administration by using user's email. I am using flutter and google firebase
I tried to use If else statement but I seem can't do it.
I have 2 model classes
User_model class
import 'package:firebase_auth/firebase_auth.dart';
class Users{
final String uid;
Users({this.uid});
}
class UserModel{
String uid;
String email;
String name;
String employeeID;
String phonenumber;
String position;
UserModel({this.uid, this.email, this.name, this.employeeID, this.phonenumber, this.position});
//receiving data from server
factory UserModel.fromMap(map){
return UserModel(
uid: map['uid'],
email: map['email'],
name: map['name'],
employeeID: map['employeeID'],
phonenumber: map['phonenumber'],
position: map['position'],
);
}
//sending data to our server
Map<String, dynamic> toMap(){
return{
'uid': uid,
'email': email,
'name' : name,
'employeeID' : employeeID,
'phonenumber' : phonenumber,
'position' : position,
};
}
}
class UserProject{
final String projectid;
final String address;
final String titleproject;
final List<String> assignedmember ;
UserProject({this.projectid, this.address, this.titleproject, this.assignedmember});
}
Project_model class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class Project{
final String address;
final String titleproject;
final List<dynamic> assignedmember;
Project({this.address, this.titleproject, this.assignedmember});
}
HomeScreen.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/data/user_model.dart';
import 'package:smartconstructionreport/screens/project_screen.dart';
import 'package:smartconstructionreport/theme.dart';
import 'package:smartconstructionreport/widget/ProjectCard.dart';
import 'package:smartconstructionreport/widget/menulist.dart';
import 'package:smartconstructionreport/service/database.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:smartconstructionreport/widget/projectlist.dart';
import 'FloorPlan.dart';
class HomeScreen extends StatefulWidget {
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
User user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
#override
void initState(){
super.initState();
FirebaseFirestore.instance
.collection("user")
.doc(user.uid)
.get()
.then((value){
this.loggedInUser = UserModel.fromMap(value.data());
setState(() {});
});
}
Widget build(BuildContext context) {
return StreamProvider<List<Project>>.value(
value: DatabaseService().projects,
child: Scaffold(
drawer: menulist(),
appBar: AppBar(
backgroundColor: kPrimaryColor,
centerTitle: true,
title: Image.asset('images/scdr logo.png',
fit: BoxFit.cover,),
),
body: SingleChildScrollView(
child: Padding(
padding: kDefaultPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 30,
),
Text(
"Hello ${loggedInUser.name},",
style: TextStyle(color: Colors.black,
fontSize: 25,
fontWeight: FontWeight.w700),
),
SizedBox(
height: 5,
),
Text(
'Have a great day ahead!',
style: TextStyle(color: Colors.black,
fontSize: 12,
),
),
SizedBox(
height: 5,
),
Text(
'Lets start working!',
style: TextStyle(color: Colors.black,
fontSize: 12,
),
),
SizedBox(
height: 30,
),
Text(
'Project Lists',
style: TextStyle(color: Colors.black,
fontSize: 25,
fontWeight: FontWeight.w700),
),
SizedBox(
height: 18,
),
ProjectList(),
],
),
),
),
),
);
}
}
ProjectList.dart
I tried to add If else statement to check if the project contains email assigned to the project. But it return null
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:provider/provider.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/screens/project_screen.dart';
import 'ProjectCard.dart';
class ProjectList extends StatefulWidget {
#override
_ProjectListState createState() => _ProjectListState();
}
class _ProjectListState extends State<ProjectList> {
User user = FirebaseAuth.instance.currentUser;
Project projectmember = Project();
#override
Widget build(BuildContext context) {
final projects = Provider.of<List<Project>>(context) ?? [];
return ListView.builder(
shrinkWrap: true,
itemCount: projects.length,
itemBuilder: (context, index) {
if (projectmember.assignedmember.contains(user.email)) {
return ProjectCard(project: projects[index],
press: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProjectScreen(),
));
},
);
};
}
);
}
}
ProjectCard.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/theme.dart';
class ProjectCard extends StatelessWidget {
final Function press;
final Project project;
ProjectCard({this.project, this.press});
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return GestureDetector(
onTap: press,
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(5.0, 15.0, 5.0, 10.0),
child: Column(
children: [
Stack(
alignment: Alignment.center,
children: [
Padding(
padding: const EdgeInsets.all(2.0),
child: Text(
project.titleproject,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
)
],
),
Divider(color: Colors.black),
Padding(
padding: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 0.0),
child: Text(
project.address,
style: TextStyle(fontSize: 14),),
),
Row(
children: [
Column(
children: [
TextButton.icon(
onPressed: (){},
icon: Icon(Icons.person,
color: kPrimaryColor,) ,
label: Text('Project Manager')),
],
),
SizedBox(width:50),
Column(
children: [
TextButton.icon(
onPressed: (){},
icon: Icon(Icons.location_pin,
color: kPrimaryColor,) ,
label: Text('MAP')),
],
)
],
),
],
),
),
);
}
}
Error
======== Exception caught by widgets library =======================================================
The method 'contains' was called on null.
Receiver: null
Tried calling: contains("rashid#fyp.com")
====================================================================================================

Related

I am not able to go to landing page after google sign in in flutter

I am trying to implement a google sign for my application using firebase.
when i press on google sign in button a pop up window appear to select the mail id when i press on my mail id i am not redirecting to LoggedInWidgit() page.
I am not getting where my code is not working
home_page.dart
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:note_app_demo/screens/login_page.dart';
import 'package:note_app_demo/utilities/logged_in_widgit.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Scaffold(
body: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasData) {
return LogedInWidgit();
} else if (snapshot.hasError) {
return Center(
child: Text('Something went Wrong!'),
);
} else {
return LOGIN_PAGE();
}
},
),
);
}
logged_in_widgit.dart
import 'package:flutter/material.dart';
import 'package:note_app_demo/utilities/scaffold.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LogedInWidgit extends StatelessWidget {
const LogedInWidgit({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser!;
return Scaffold(
appBar: AppBar(
title: Text('Logged In'),
centerTitle: true,
actions: [
TextButton(
onPressed: () {},
child: Text('Logout'),
)
],
),
body: Container(
alignment: Alignment.center,
color: Colors.blueGrey.shade900,
child: Column(
children: [
Text(
'Profile',
style: TextStyle(fontSize: 24),
),
SizedBox(
height: 32,
),
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(user.photoURL!),
),
SizedBox(
height: 8,
),
Text(
'Name: ' + user.displayName!,
style: TextStyle(color: Colors.white, fontSize: 16),
),
SizedBox(
height: 8,
)
],
),
),
);
}
}
main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:note_app_demo/provider/google_sign_in.dart';
import 'package:note_app_demo/screens/landing_page.dart';
import 'package:flutter/services.dart';
import 'package:note_app_demo/screens/login_page.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => ChangeNotifierProvider(
create: (context) => GoogleSignInProvider(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Studiac',
home: LOGIN_PAGE(),
),
);
}
login_page.dart
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:note_app_demo/provider/google_sign_in.dart';
import 'package:note_app_demo/screens/landing_page.dart';
import 'package:note_app_demo/button.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';
class LOGIN_PAGE extends StatelessWidget {
const LOGIN_PAGE({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: ElevatedButton.icon(
icon: FaIcon(
Icons.email,
color: Colors.blue,
),
label: Text('Sign Up with Email'),
onPressed: () {},
style: ElevatedButton.styleFrom(
primary: Colors.tealAccent,
onPrimary: Colors.black,
minimumSize: Size(double.infinity, 50),
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: ElevatedButton.icon(
icon: FaIcon(
FontAwesomeIcons.google,
color: Colors.red,
),
label: Text('Sign Up with Google'),
onPressed: () {
final provider = Provider.of<GoogleSignInProvider>(context,
listen: false);
provider.googleLogin();
},
style: ElevatedButton.styleFrom(
primary: Colors.tealAccent,
onPrimary: Colors.black,
minimumSize: Size(double.infinity, 50),
),
),
),
],
),
),
),
);
}
}
google_sign_in.dart
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
class GoogleSignInProvider extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
//getter to get google sign in
GoogleSignInAccount get user => _user!;
Future googleLogin() async {
try {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
print(e.toString());
}
notifyListeners();
}
Future logout() async {
await googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
}

Edit User Profile Page and Profile Picture. Using Real-Time Database flutter

I am trying to pull user data from my UserProfileBrowse Data model and display it on my user profile edit page. Including the image. I also want to update the data into my real-time Database.
THIS IS MY DATA MODEL
class UserProfileBrowse {
String userId;
int age;
String name;
String email;
String imageUrl;
UserProfileBrowse(
this.userId,
this.age,
this.name,
this.email,
this.imageUrl,
);
Map<dynamic, dynamic> toJson() => <dynamic, dynamic>{
'userId': userId,
'age': age,
'name': name,
'email': email,
'imageUrl' : imageUrl,
};
}
THIS IS MY USER PROFILE EDIT PAGE
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/auth.dart';
import 'home.dart';
import 'settings.dart';
import 'package:shadow_app_project/data_models/user_profile_browse.dart';
import 'package:shadow_app_project/image_selection/user_edit_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class SettingsUI extends StatelessWidget {
const SettingsUI({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: "Setting UI",
home: EditProfilePage(),
);
}
}
class EditProfilePage extends StatefulWidget {
const EditProfilePage({Key? key}) : super(key: key);
#override
_EditProfilePageState createState() => _EditProfilePageState();
}
class _EditProfilePageState extends State<EditProfilePage> {
String currentUser = (Auth().auth.currentUser as User).email.toString();
TextEditingController displayNameController = TextEditingController();
TextEditingController ageController = TextEditingController();
bool isLoading = false;
User? user;
UserProfileBrowse? userModel;
String? imageUrl;
final refDatabase = FirebaseDatabase.instance;
bool showPassword = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 1,
leading: IconButton(
icon: const Icon(
Icons.arrow_back,
color: Colors.green,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => const SettingsPage()));
},
),
actions: [
IconButton(
icon: const Icon(
Icons.settings,
color: Colors.green,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => const SettingsPage()));
},
),
],
),
body: Container(
padding: const EdgeInsets.only(left: 16, top: 25, right: 16),
child: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: ListView(
children: [
const Text(
"Edit Profile",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
const SizedBox(
height: 15,
),
Container(
width: 130,
height: 130,
decoration: BoxDecoration(
border: Border.all(
width: 4,
color: Theme.of(context).scaffoldBackgroundColor),
boxShadow: [
BoxShadow(
spreadRadius: 2,
blurRadius: 10,
color: Colors.black.withOpacity(0.1),
offset: const Offset(0, 10))
],
shape: BoxShape.circle,
image: const DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
"https://images.pexels.com/photos/3307758/pexels-photo-3307758.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250",
))),
),
const SizedBox(
height: 35,
),
TextField(
decoration: const InputDecoration(
labelText: "Name",
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
hintText: 'Input Name',
),
controller: displayNameController,
keyboardType: TextInputType.name,
),
TextField(
decoration: const InputDecoration(
labelText: "Age",
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
hintText: 'Input Age',
),
controller: ageController,
//
keyboardType: TextInputType.number,
),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text("Email: ", style: TextStyle(fontSize: 20),),
),
const SizedBox(
height: 35,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {},
child: const Text("CANCEL",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.black)),
),
TextButton(
onPressed: () {
FirebaseDatabase.instance.ref()
.child('useProfileBrowse')
.child(user!.uid)
.update({
'name': displayNameController.text //yes I know.
});
FirebaseDatabase.instance.ref()
.child('useProfileBrowse')
.child(user!.uid)
.update({
'age': ageController.text //yes I know.
});
},
child: const Text(
"SAVE",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.white),
),
)
],
)
],
),
),
),
);
}
}
I am thinking to use a StreamBuilder in my body: with stream: FirebaseDatabase.instance.ref().child('userProfileBrowse').child(user!.uid).onValue,
Any idea how can I display User profile Imageurl, name, and age from my real-time Database
And also edit the information using stream builder or any other method
I have just coded the UI for my profile edit page. I just want someone to help me retrieve data from my data model class and display it on my user edit page. A single line to display just a name from my data model will help a lot to understand how retrieving data works. I have already saved data(imageUrl, name, age) into my data models during the signup process. Just want to display it
full example with StreamProvider :
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Person {
Person({required this.name, required this.initialAge});
final String name;
final int initialAge;
Stream<String> get age async* {
var i = initialAge;
while (i < 85) {
await Future.delayed(const Duration(seconds: 1), () {
i++;
});
yield i.toString();
}
}
}
void main() {
runApp(
StreamProvider<String>(
create: (_) => Person(name: 'Yohan', initialAge: 25).age,
initialData: 25.toString(),
catchError: (_, error) => error.toString(),
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Future Provider"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Consumer<String>(
builder: (context, String age, child) {
return Column(
children: <Widget>[
const Text("Watch Yohan Age..."),
const Text("name: Yohan"),
Text("age: $age"),
],
);
},
),
),
),
);
}
}
You already started to use the Provider as a state management, so I'd recommend using StreamProvider like this:
StreamProvider<String>(
create: (_) => Profile(name: 'Yohan', initialImageURL: ''),
initialData: ''.toString(),
catchError: (_, error) => error.toString(),
child: child(),
builder: (context) {
// Pretend this is loading data and reporting the percent loaded.
},
),
)
or you can just notify the UI every time you have got a change from the firebase using ChangeNotifier,
for examples, visit Docs

"RangeError (index)" when trying to replicate the Netflix UI by using Flutter and Firebase

I'm making clone of Netflix-UI by using flutter and firebase. And I have some problem about it. I've been trying to solve it for 1 week but I can't.
When I run this app it has message
RangeError (index): Invalid value: Valid value range is empty: 0'
I upload my project in github.. plz help
https://github.com/woosihyeon/fluuterandfirebase_app
This is the code:
import 'package:flutter/material.dart';
import 'package:fluuterandfirebase_app/model_movie/model_movie.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:fluuterandfirebase_app/widget/carousel_slider.dart';
import 'package:fluuterandfirebase_app/widget/circle_slider.dart';
import 'package:fluuterandfirebase_app/widget/box_slider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
Stream<QuerySnapshot> streamData;
#override
void initState() {
super.initState();
streamData = firebaseFirestore.collection('movies').snapshots();
}
Widget _fetchData(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('movies').snapshots(),
builder: (BuildContext context,AsyncSnapshot<QuerySnapshot> snapshot){
if(!snapshot.hasData) return LinearProgressIndicator();
return _buildBody(context, snapshot.data.docs);
},
);
}
Widget _buildBody(BuildContext context,List<DocumentSnapshot> snapshot){
List<Movie> movies = snapshot.map((d) => Movie.fromSnapshot(d)).toList();
return ListView(
children:<Widget>[
Stack(
children: <Widget>[
CarouseImage(movies: movies),
TopBar(),
],
),
CircleSlider(
movies: movies,
),
BoxSlider(
movise: movies,
),
],
);
}
#override
Widget build(BuildContext context) {
return _fetchData(context);
}
}
class TopBar extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(20, 7, 20, 7),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Image.asset(
'images/bbongflix_logo.png',
fit: BoxFit.contain,
height: 25.0,
),
Container(
padding: EdgeInsets.only(right: 1),
child: Text(
'TV 프로그램',
style: TextStyle(fontSize: 14.0),
),
),
Container(
padding: EdgeInsets.only(right: 1),
child: Text(
'영화',
style: TextStyle(fontSize: 14.0),
),
),
Container(
padding: EdgeInsets.only(right: 1),
child: Text(
'내가 찜한 콘텐츠',
style: TextStyle(fontSize: 14.0),
),
),
],
),
);
}
}

How to save user data in cloud fire store in flutter

I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:
User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.
Please I'm a beginner and I have no idea how to pull this off.
Here is the code for reference:
cloud_firebase.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.add({'displayName': displayName, 'uid': uid});
return;
}
auth.dart
import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const AuthScreen(),
);
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen>
with SingleTickerProviderStateMixin {
AnimationController _controller;
ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: LitAuth.custom(
onAuthSuccess: () {
Navigator.of(context).pushReplacement(HomeScreen.route);
},
child: Stack(
children: [
SizedBox.expand(
child: CustomPaint(
painter: BackgroundPainter(),
)),
Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800),
child: ValueListenableBuilder<bool>(
valueListenable: showSignInPage,
builder: (context, value, child) {
return PageTransitionSwitcher(
reverse: !value,
duration: Duration(milliseconds: 800),
transitionBuilder:
(child, animation, secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: value
? SignIn(
key: ValueKey('SignIn'),
onRegisterClicked: () {
context.resetSignInForm();
showSignInPage.value = false;
_controller.forward();
},
)
: Register(
key: ValueKey('Register'),
onSignInPressed: () {
context.resetSignInForm();
showSignInPage.value = true;
_controller.reverse();
},
),
);
},
),
),
),
],
),
),
);
}
}
splash.dart
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const SplashScreen(),
);
#override
Widget build(BuildContext context) {
final user = context.watchSignedInUser();
user.map(
(value) {
_navigateToHomeScreen(context);
},
empty: (_) {
_navigateToAuthScreen(context);
},
initializing: (_) {},
);
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
void _navigateToAuthScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(AuthScreen.route),
);
}
void _navigateToHomeScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(HomeScreen.route),
);
}
}
edit_profile.dart
import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';
class Profile extends StatefulWidget {
const Profile({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const Profile(),
);
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
// UserModel _currentUser = locator.get<UserController>().currentUser;
// File _image;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Edit Profile'),
),
body: Builder(
builder: (context) => Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Column(
children: <Widget>[
Text(
'Hey there',
style: TextStyle(color: Palette.lightGreen, fontSize: 20),
)
],
),
SizedBox(
height: 20,
),
Expanded(
flex: 8,
child: ListView(
children: [
Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: TextFormField(
style: const TextStyle(
fontSize: 18,
color: Colors.green,
),
decoration: signInInputDecoration(
hintText: 'New Username',
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
elevation: 4,
color: Colors.red,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
),
RaisedButton(
elevation: 4,
color: Palette.lightGreen,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
),
],
),
],
),
),
],
),
),
),
);
}
}
to save user data to document in firebase using uuid for document name the below code will work.
if you are confused about how to use the code in your app its simple.
just follow the steps:
call userSetup Function from onpress while passing the display name data.
how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.
onPress:(){
userSetup(displayName:"zakriakhan");
}
userSteup Function
Future<void> userSetup(String displayName) async {
//firebase auth instance to get uuid of user
FirebaseAuth auth = FirebaseAuth.instance.currentUser();
//now below I am getting an instance of firebaseiestore then getting the user collection
//now I am creating the document if not already exist and setting the data.
FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
{
'displayName': displayName, 'uid': uid
})
return;
}

Storing the image as url and posting it in my app?

Ill try and provide as much code as possible. (mainly regarding the image ill be using "other data" instead of posting non needed code besides the image)
So in my app I have a File image; provider and im having issues with getting to display it on my app. Im unable to pass the File image path into firebase and its causing my app to crash when I try Fetching the data from firebase. Ill try providing as much code as possible.
Here is my provider:
import 'dart:io';
class AddCar {
// other data
File image;
AddCar({
// other data
this.image,
});
}
Here is my provider code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import '../add_ons/add_car.dart';
List<AddCar> _cars = [];
class Cars with ChangeNotifier {
List<AddCar> get cars {
return [..._cars];
}
Future<void> fetchAndSetCars() async {
const url = 'https://mycustomlink.firebaseio.com/cars.json';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
var loadedCars = extractedData
.map<String, AddCar>((carId, carData) => MapEntry(
carId,
AddCar(
// other data
image: File(carData['image']),
)))
.values
.toList();
_cars = loadedCars;
print(extractedData);
print(loadedCars);
notifyListeners();
} catch (error) {
throw (error);
}
}
AddCar findById(String id) {
return _cars.firstWhere((carProd) => carProd.id == id);
}
void addCar(AddCar car) {
const url = 'https://mycustomlink.firebaseio.com/cars.json';
http.post(
url,
body: json.encode({
// other data
'image': car.image.toString(),
}),
);
final newCar = AddCar(
// other data
image: car.image,
);
_cars.insert(0, newCar);
notifyListeners();
}
}
here is my form where the user enters data for it to be displayed:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/app_localization.dart';
import 'package:google_fonts_arabic/fonts.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as syspaths;
import '../add_ons/add_car.dart';
import '../providers/car_provider.dart';
import '../drawer/drawer.dart';
import '../screens/cars_screen.dart';
import '../app_localization.dart';
class CreateCar extends StatefulWidget {
static const routeName = '/create-car';
#override
_CreateCarState createState() => _CreateCarState();
}
class _CreateCarState extends State<CreateCar> {
final _name = TextEditingController();
final _price = TextEditingController();
final _address = TextEditingController();
String img;
static Future<String> fileToB64(File f) async {
List<int> imageBytes = f.readAsBytesSync();
return base64Encode(
imageBytes,
);
}
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
fileToB64(data.image).then((d) {
setState(() {
img = d; //base64Decode(d);
});
});
}
final _form = GlobalKey<FormState>();
int currStep = 0;
static AddCar data = new AddCar(
id: null,
date: DateTime.now(),
sponsNum: '',
);
void _saveForm() {
final isValid = _form.currentState.validate();
if (!isValid) {
return;
}
_form.currentState.save();
Provider.of<Cars>(context, listen: false).addCar(data);
Navigator.of(context).pushNamed(CarsScreen.routeName);
print('this works');
}
#override
Widget build(BuildContext context) {
List<Step> steps = [
Step(
title: Text(
AppLocalizations.of(context).createTabTitle,
),
isActive: true,
state: StepState.indexed,
content: Column(
children: <Widget>[
// other data
],
),
),
Step(
title: Text(
AppLocalizations.of(context).createCarDetails,
),
isActive: true,
state: StepState.indexed,
content: Column(
children: <Widget>[
// other data
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 25.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.circular(50.0),
),
child: FlatButton(
child: Text(AppLocalizations.of(context).createAddImages),
onPressed: _takePicture,
),
),
)
],
)
],
),
),
];
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
AppLocalizations.of(context).createCarPageTitle,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: ArabicFonts.Tajawal,
package: 'google_fonts_arabic',
),
),
actions: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: _saveForm,
),
IconButton(
icon: Icon(Icons.arrow_forward),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
],
),
drawer: MyDrawer(),
body: Row(
children: <Widget>[
Form(
key: _form,
child: Expanded(
child: Stepper(
steps: steps,
type: StepperType.vertical,
currentStep: this.currStep,
onStepContinue: () {
setState(() {
if (currStep < steps.length - 1) {
currStep = currStep + 1;
} else {
// currStep = 0;
}
});
},
onStepCancel: () {
setState(() {
if (this.currStep > 0) {
this.currStep = this.currStep - 1;
} else {
this.currStep = 0;
}
});
},
onStepTapped: (step) {
setState(() {
currStep = step;
});
},
),
),
),
],
),
);
}
}
which is later passed into my "CarItem" that will display my code:
import 'package:flutter/material.dart';
import 'package:google_fonts_arabic/fonts.dart';
import '../icons/MyIcons.dart';
import 'dart:io';
import '../details/car_details.dart';
import '../app_localization.dart';
class CarItem extends StatelessWidget {
final File image;
CarItem(
this.image,
);
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).primaryColor, width: 2.0),
),
),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 245, 245, 245),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(17.0, 4.0, 17.0, 4.0),
child: Row(
textDirection: TextDirection.rtl,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
// other data
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.35,
height: MediaQuery.of(context).size.width * 0.35,
child: GestureDetector(
child: Image.file(
image,
fit: BoxFit.fill,
),
onTap: () {
Navigator.of(context).pushNamed(
MyCarDetails.routeName,
arguments: id,
);
},
),
),
Container(
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.all(0),
padding: const EdgeInsets.fromLTRB(22.0, 5.0, 22.0, 0),
child: Column(
children: <Widget>[
// other data
],
),
),
],
),
),
],
),
],
),
);
}
}
this code gets called by a list that will call the code and display it in my app:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts_arabic/fonts.dart';
import '../providers/car_provider.dart';
import '../widget/car_item.dart';
class CarsList extends StatefulWidget {
#override
_CarsListState createState() => _CarsListState();
}
class _CarsListState extends State<CarsList> {
#override
Widget build(BuildContext context) {
final carsData = Provider.of<Cars>(context);
final car = carsData.cars;
return car.isEmpty
? Center(
child: Text(
'no data yet available',
style: TextStyle(
fontFamily: ArabicFonts.Tajawal,
fontWeight: FontWeight.bold,
package: 'google_fonts_arabic',
),
))
: ListView.builder(
padding: const EdgeInsets.only(bottom: 47.0),
itemCount: car.length,
itemBuilder: (ctx, i) => CarItem(
// other data
car[i].image,
),
);
}
}
this is the error i keep getting when It tries to display fetched data:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building CarItem(dirty, dependencies: [_LocalizationsScope-[GlobalKey#31697], MediaQuery, _InheritedTheme]):
The method '+' was called on null.
Receiver: null
Tried calling: +("25")
User-created ancestor of the error-causing widget was
ListView
lib\home_parts\cars_area.dart:49
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 CarItem.build
package:flutter_app/widget/car_item.dart:151
#2 StatelessElement.build
package:flutter/…/widgets/framework.dart:4009
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3941
#4 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
...
════════════════════════════════════════════════════════════════════════════════
How can I fix this? is the issue in how im passing the data to firebase and displaying it on my app?

Resources