Flutter : problem with creating a document in firestore with riverhooks - flutter

whenever i want to make a document in firestore it wo't let me , i think its something that i did with riverpod and with hooks
here is the code :
onPressed: () async {
currentOrganization.when(
data: (organization) async {
_post.value = _post.value
.copyWith(creator: organization);
print(_post.value);
String imageid = uuid.v4();
pickedImage = await ImagePicker()
.getImage(
source: ImageSource.gallery,
maxWidth: 1920,
maxHeight: 1200,
imageQuality: 80);
Reference reference = FirebaseStorage
.instance
.ref()
.child("$imageid");
UploadTask uploadTask = reference
.putFile(File(pickedImage.path));
await uploadTask.then((res) async {
imageUrl = await reference
.getDownloadURL();
});
_post.value = _post.value
.copyWith(picture: imageUrl);
},
loading: () =>
const CircularProgressIndicator(),
error: (error, stack) => Center(
child: Text("$error"),
));
},
),
),
GestureDetector(
onTap: () async {
context
.read(createPostUSeCaseProvider)
.execute(CreatePostUseCaseInput(
uuid.v4(),
_post.value.description,
_post.value.title,
_post.value.creator,
_post.value.likes,_post.value.picture))
.then(
(result) => result.fold(
(failure) {
print('FAILURE: $failure');
toast("Please try again");
},
(unit) {
toast(" successfully");
},
),
);
},
when i delete the currentOrganizationProvider everything works like charm
here is the
UseCase
import 'package:dartz/dartz.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:takaful/application/core/use_cases/i.use_case.dart';
import 'package:takaful/application/post/use_case/create_post/create_post.input.dart';
import 'package:takaful/application/providers/post.repository.provider.dart';
import 'package:takaful/domain/core/i.failure.dart';
import 'package:takaful/domain/model/post.dart';
import 'package:takaful/domain/post/i.post.repository.dart';
final createPostUSeCaseProvider = Provider((ref) =>
CreatePostUseCase(postRepository: ref.watch(postRepositoryProvider)));
class CreatePostUseCase implements IUseCase<CreatePostUseCaseInput, Unit> {
final IPostRepository _postRepository;
CreatePostUseCase({IPostRepository postRepository})
: _postRepository = postRepository;
#override
Future<Either<IFailure, Unit>> execute(input) async {
return await _postRepository.createPost(
description: input.discreption,
model: input.model,
id: input.id,
title: input.title,
likes: input.likes,
picture: input.picture);
}
}
and the
infrastructure code :
Future<Either<UserFailures, Unit>> createPost({String id, String title, String description, OrganizationModel model, int likes,String picture}) async{
try {
await _firestore.collection(collection).doc().set({
"id":id,
"title":title,
"description":description,
"creator":model,
"likes":likes,
"picture":picture
});
return right(unit);
} catch (error) {
return left(UserFailures.serverError());
}
}
when i delete the the provider everything works , any idea , and i need the model !

Related

Image cropper not working in GetxController

The following is the code i was trying to implement in. The future method pickImage i guess it is the one having the problem. I am extending the class with GetxController. The method is expected to pick and crop the selected image using the image cropper, and then set the cropped image to the imageFile variable if the cropping was successful.
import 'dart:io';
import 'package:pamoja/app/data/const.dart';
import 'package:pamoja/app/data/firebase/firebase_functions.dart';
import 'package:pamoja/app/data/global_widgets/indicator.dart';
import 'package:pamoja/app/models/advert_model.dart';
import 'package:pamoja/app/modules/my_adverts/controllers/my_adverts_controller.dart';
import 'package:pamoja/app/routes/app_pages.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
class UploadBlogController extends GetxController {
TextEditingController title = TextEditingController();
TextEditingController description = TextEditingController();
TextEditingController location = TextEditingController();
TextEditingController category = TextEditingController();
TextEditingController price = TextEditingController();
TextEditingController phone = TextEditingController();
final FirebaseFunctions _functions = FirebaseFunctions();
File? imageFile;
Future<void> pickImage() async {
try {
ImagePicker _picker = ImagePicker();
await _picker.pickImage(source: ImageSource.gallery).then((value) async {
if (value != null) {
File? croppedFile = await ImageCropper().cropImage(
sourcePath: value.path,
aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 700,
maxHeight: 700,
// saveCircleCroppedImage: true,
);
if (croppedFile != null) {
imageFile = croppedFile;
update();
}
}
});
} catch (e) {
showAlert("$e");
}
}
void createBlog() async {
if (title.text.isNotEmpty && description.text.isNotEmpty) {
if (imageFile != null && imageFile != "") {
Indicator.showLoading();
await _functions
.uploadBlog(
title.text,
description.text,
imageFile!,
price.text,
category.text,
location.text,
phone.text,
)
.then((value) {
Indicator.closeLoading();
showAlert("Your advert created sucessfully");
// Get.back();
Get.toNamed(Routes.HOME);
});
} else {
showAlert("Image is required");
}
} else {
showAlert("All fields are required");
}
}
void editBlog(BlogsModel model) async {
Indicator.showLoading();
if (title.text.isNotEmpty && description.text.isNotEmpty) {
if (imageFile == null) {
Map<String, dynamic> map = {
'title': title.text,
'description': description.text,
};
await _functions.editBlog(model.id, map).then((value) {
Get.toNamed(Routes.HOME);
showAlert("Your ads Updated Sucessfully");
});
} else {
String imageUrl = await _functions.uploadImage(imageFile!);
Map<String, dynamic> map = {
'title': title.text,
'description': description.text,
'img': imageUrl,
};
await _functions.editBlog(model.id, map).then((value) {
Get.toNamed(Routes.HOME);
showAlert("Your Advert Updated Sucessfully");
});
}
} else {
showAlert("All fields are required");
}
Indicator.closeLoading();
updateData();
}
void updateData() {
Get.back();
Get.toNamed(Routes.HOME);
if (Get.isRegistered<MyBlogsController>()) {
final controller = Get.find<MyBlogsController>();
controller.myBlogs = [];
Indicator.showLoading();
controller.getMyBlogData();
}
}
}
this i created reusable single-tone code for my entire app to pick media image or video. you can try or modify according your requirement.
// Dart imports:
import 'dart:io';
// Package imports:
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
// Project imports:
import 'package:app/utils/export_utils.dart';
class MediaPicker {
MediaPicker._();
static const supportedImageFormates = [".jpeg", ".png"];
static const supportedVedioFormates = [".mp4"];
static final picker = ImagePicker();
// Single image / video selection
static Future<File?> pickMedia({
required ImageSource source,
bool isVideo = false,
bool isEditing = false,
}) async {
try {
final pickMedia = !isVideo
? await picker.pickImage(source: source)
: await picker.pickVideo(source: source);
if (pickMedia != null) {
return isEditing
? await editImage(file: File(pickMedia.path))
: File(pickMedia.path);
} else {
return null;
}
} catch (ex) {
"Pick Media error: $ex".printLog();
return null;
}
}
static Future<File> editImage({required File file}) async {
final CroppedFile? croppedFile = await ImageCropper().cropImage(
sourcePath: file.path,
uiSettings: [
AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: ColorConst.themePrimaryColor,
toolbarWidgetColor: ColorConst.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
IOSUiSettings(
title: 'Cropper',
),
],
);
if (croppedFile != null) {
return File(croppedFile.path);
} else {
return file;
}
}
}
Usage add call method on button tap with Future & async method
Future<void> btnPickImageTap() async {
final File? selectImageFile = await MediaPicker.pickMedia(
source: ImageSource.gallery,
isEditing: true, // Default false
);
}
source: ImageSource.camera - to pick image from camera.
isEditing: false - avoid image cropping functionality.
isVideo: to pick video from gallery / camera.
Make sure following permission added for both platforms
Andriod- AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/> //Camera
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> // Read Storage
iOS Runner/info.plist
<key>NSCameraUsageDescription</key>
<string>App require camera permission to update profile pic</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>App require gallery permission to update profile pic</string>
As package mentioned in image_cropper add bellow code in AndroidManifest.xml under <applcaiton> TAG
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"/>
I modified it following your instruction it worked. The following is a sample modification
Future<void> pickImage() async {
try {
ImagePicker _picker = ImagePicker();
await _picker.pickImage(source: ImageSource.gallery).then((value) async {
if (value != null) {
imageFile = File(value.path);
showAlert(imageFile.toString());
editImage(imageFile: imageFile);
// cropImage(imageFile);
} else {
showAlert("No image selected");
}
});
} catch (e) {
showAlert("$e");
}}
Future<void> editImage({required File? imageFile}) async {
final File? croppedFile = await ImageCropper().cropImage(
sourcePath: imageFile!.path,
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Advert Image',
toolbarColor: Colors.green.shade400,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
),
);
if (croppedFile != null) {
imageFile = File(croppedFile.path);
update();
} else {
// update();
}}

App notification badge update using Firebase Messaging

I'm using flutter_app_badger and Firebase Messaging to set a notification system which would update number in app badger when a new notification is coming. I'm working in Flutterflow so my approach might be a bit awkward. So far I managed to do two things:
Create a separate function in the app which updates app badger while app is working;
Set the notification system that is triggered by the action in app;
But I can't combine the two. I have the following push_notification_handler code and trying how to put FlutterAppBadger.updateBadgeCount() function it.
import 'dart:async';
import 'dart:convert';
import 'serialization_util.dart';
import '../backend.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_util.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import '../../index.dart';
import '../../main.dart';
final _handledMessageIds = <String?>{};
class PushNotificationsHandler extends StatefulWidget {
const PushNotificationsHandler({Key? key, required this.child})
: super(key: key);
final Widget child;
#override
_PushNotificationsHandlerState createState() =>
_PushNotificationsHandlerState();
}
class _PushNotificationsHandlerState extends State<PushNotificationsHandler> {
bool _loading = false;
Future handleOpenedPushNotification() async {
if (isWeb) {
return;
}
final notification = await FirebaseMessaging.instance.getInitialMessage();
if (notification != null) {
await _handlePushNotification(notification);
}
FirebaseMessaging.onMessageOpenedApp.listen(_handlePushNotification);
}
Future _handlePushNotification(RemoteMessage message) async {
if (_handledMessageIds.contains(message.messageId)) {
return;
}
_handledMessageIds.add(message.messageId);
if (mounted) {
setState(() => _loading = true);
}
try {
final initialPageName = message.data['initialPageName'] as String;
final initialParameterData = getInitialParameterData(message.data);
final pageBuilder = pageBuilderMap[initialPageName];
if (pageBuilder != null) {
final page = await pageBuilder(initialParameterData);
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => page),
);
}
} catch (e) {
print('Error: $e');
} finally {
if (mounted) {
setState(() => _loading = false);
}
}
}
#override
void initState() {
super.initState();
handleOpenedPushNotification();
}
#override
Widget build(BuildContext context) => _loading
? Container(
color: FlutterFlowTheme.of(context).primaryBtnText,
child: Image.asset(
'assets/images/Screen_Shot_2022-11-22_at_12.59.57.png',
fit: BoxFit.contain,
),
)
: widget.child;
}
final pageBuilderMap = <String, Future<Widget> Function(Map<String, dynamic>)>{
'SignInSignUpPage': (data) async => SignInSignUpPageWidget(),
'ForgotPasswordPage': (data) async => ForgotPasswordPageWidget(),
'ContactsListPage': (data) async => ContactsListPageWidget(
tabToOpen: getParameter(data, 'tabToOpen'),
),
'SyncProcessPage': (data) async => SyncProcessPageWidget(),
'SyncConfirmationPage': (data) async => SyncConfirmationPageWidget(),
'ContactDetailsPage': (data) async => ContactDetailsPageWidget(
idReference: getParameter(data, 'idReference'),
comment: getParameter(data, 'comment'),
),
'ContactDeletePage': (data) async => ContactDeletePageWidget(
idReference: getParameter(data, 'idReference'),
comment: getParameter(data, 'comment'),
),
'ContactInvitationPage': (data) async => ContactInvitationPageWidget(
idReference: getParameter(data, 'idReference'),
),
'AddConfirmationAfterInvitePage': (data) async =>
AddConfirmationAfterInvitePageWidget(
uID: getParameter(data, 'uID'),
phraseState: getParameter(data, 'phraseState'),
),
'AddContactsOptionPage': (data) async => AddContactsOptionPageWidget(),
'SearchNewContactsPage': (data) async => SearchNewContactsPageWidget(),
'NewContactInvitationConfirmationPage': (data) async =>
NewContactInvitationConfirmationPageWidget(),
'NewContactScanPage': (data) async => NewContactScanPageWidget(),
'AddConfirmationAfterScanPageNew': (data) async =>
AddConfirmationAfterScanPageNewWidget(
uID: getParameter(data, 'uID'),
phraseState: getParameter(data, 'phraseState'),
),
'AddConfirmationAfterScanPageOld': (data) async =>
AddConfirmationAfterScanPageOldWidget(
uID: getParameter(data, 'uID'),
phraseState: getParameter(data, 'phraseState'),
),
'ShareProfileOptionsPage': (data) async => ShareProfileOptionsPageWidget(),
'InAppQRcodeSharePage': (data) async => InAppQRcodeSharePageWidget(),
'WebQRcodeSharePage': (data) async => WebQRcodeSharePageWidget(),
'ProfileEditPage': (data) async => ProfileEditPageWidget(),
'GameSettingsPage': (data) async => GameSettingsPageWidget(),
'GamePage': (data) async => GamePageWidget(),
'TutorialPage': (data) async => TutorialPageWidget(),
'AboutPage': (data) async => AboutPageWidget(),
'FAQPage': (data) async => FAQPageWidget(),
'PrivacyPolicyPage': (data) async => PrivacyPolicyPageWidget(),
};
bool hasMatchingParameters(Map<String, dynamic> data, Set<String> params) =>
params.any((param) => getParameter(data, param) != null);
Map<String, dynamic> getInitialParameterData(Map<String, dynamic> data) {
try {
final parameterDataStr = data['parameterData'];
if (parameterDataStr == null ||
parameterDataStr is! String ||
parameterDataStr.isEmpty) {
return {};
}
return jsonDecode(parameterDataStr) as Map<String, dynamic>;
} catch (e) {
print('Error parsing parameter data: $e');
return {};
}
}
Would be super grateful for any advice!

Repository testing with mocktail and flutter test - I'm trying to write a test for my repository but I keep getting an error 'No such mrthod'

error message Repository testing with mocktail and flutter test - I'm trying to write a test for my repository but I keep getting an error 'No such method'
I've tried with ThenAnswer as well but it still won't go through. I'll appreciate any help :)
That's what my code looks like :
Test file:
`import 'package:curlzzz_new/data_source/remote_watch_data_source.dart';
import 'package:curlzzz_new/models/watch_model.dart';
import 'package:curlzzz_new/repositories/watch_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockWatchDataSource extends Mock implements RemoteWatchDataSource {}
void main() {
//sut to System under testing
late WatchRepository sut;
late MockWatchDataSource dataSource;
setUp(() {
dataSource = MockWatchDataSource();
sut = WatchRepository(dataSource);
});
group('getWatchStream', () {
test('should return a stream of WatchModels', () {
//1
when(() => dataSource.getRemoteWatchStream()).thenThrow(
(_) => Stream.value([
WatchModel(title: 'titanic', id: '555'),
WatchModel(title: 'top gun', id: '555'),
WatchModel(title: 'matrix', id: '111')
]),
);
//2
final results = sut.getWatchStream();
//3
expect(results, [
WatchModel(title: 'titanic', id: '555'),
WatchModel(title: 'top gun', id: '555'),
WatchModel(title: 'matrix', id: '111')
]);
});
});
}
`
Repository:
import 'package:curlzzz_new/data_source/remote_watch_data_source.dart';
import 'package:curlzzz_new/models/watch_model.dart';
class WatchRepository {
WatchRepository(this.remoteDataSource);
final RemoteWatchDataSource remoteDataSource;
Stream<List<WatchModel>> getWatchStream() {
return remoteDataSource.getRemoteWatchStream().map((querySnapshot) {
return querySnapshot.docs.map((doc) {
return WatchModel(title: doc['title'], id: doc.id);
}).toList();
});
}
Future<void> addMovies({
required String title,
}) {
return remoteDataSource.addRemoteWatchData(title: title);
}
Future<void> dismiss({required String id}) {
return remoteDataSource.dismissRemoteData(id: id);
}
}
Data Source:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class RemoteWatchDataSource {
Stream<QuerySnapshot<Map<String, dynamic>>> getRemoteWatchStream() {
final userID = FirebaseAuth.instance.currentUser?.uid;
if (userID == null) {
throw Exception('User is not logged in');
}
return FirebaseFirestore.instance
.collection('users')
.doc(userID)
.collection('movies')
.snapshots();
}
Future<DocumentReference<Map<String, dynamic>>?> addRemoteWatchData({
required String title,
}) async {
final userID = FirebaseAuth.instance.currentUser?.uid;
if (userID == null) {
throw Exception('User is not logged in');
}
return FirebaseFirestore.instance
.collection('users')
.doc(userID)
.collection('movies')
.add(
{'title': title},
);
}
Future<void> dismissRemoteData({required String id}) async {
final userID = FirebaseAuth.instance.currentUser?.uid;
if (userID == null) {
throw Exception('User is not logged in');
}
return FirebaseFirestore.instance
.collection('users')
.doc(userID)
.collection(
'movies',
)
.doc(id)
.delete();
}
}
It seems like a a problem with the closure type.
try this. don't combine 2 functions in a single test.
group('getWatchStream', () {
test('should return a stream of WatchModels', () async {
final List<WatchModel> models = [
WatchModel(title: 'titanic', id: '555'),
WatchModel(title: 'top gun', id: '555'),
WatchModel(title: 'matrix', id: '111')
];
//1
when(() => dataSource.getRemoteWatchStream()).thenAnswer(
(_) => Stream.value(models),
);
//2
await dataSource.getRemoteWatchStream();
//3
expect(dataSource.getRemoteWatchStream, emits(models) );
});
});

How to setup blocTest for a feature that requires authentication?

So I'm implementing blocTesting for my flutter project and I'm using real apis in testing as that is what I've been asked to do. Apparently when I'm trying out blocTesting for a feature that requires authentication the api is giving back a null response but in the running app it is working fine...
I'm adding the respective files below for the same. Also the name of feature is client and I'm trying to fetch all clients here.
Client_bloc_test.dart
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:injectable/injectable.dart' as inject;
import 'package:mynovatium/app/helper/injections/shared_preference/shared_preference_injection_configuration.dart';
import 'package:mynovatium/features/buy/models/test_model.dart';
import 'package:mynovatium/features/client/bloc/client_bloc.dart';
import 'package:mynovatium/features/client/models/private_client_model.dart';
import 'package:mynovatium/features/login/bloc/authentication/authentication_bloc.dart';
import 'package:mynovatium/features/login/repositories/authentication_repository.dart';
void main() async {
await configureInjection(inject.Environment.test);
final AuthenticationBloc authenticationBloc = AuthenticationBloc();
group('ClientBloc', () {
late PrivateClientModel client;
test('initial state of the bloc is [SignupInitial]', () {
expect(
ClientBloc(authenticationBloc: authenticationBloc).state,
ClientInitial(),
);
});
group('ClientCreateClient', () {
blocTest<ClientBloc, ClientState>(
'emits [ClientLoadInProgress, ClientLoadSuccess] '
'state when successfully fetched clients',
setUp: () async {
client = PrivateClientModel(1, List<TestModel>.empty(), createdAt: DateTime.now(), gender: 'Male', firstName: 'Nikunj', lastName: 'goyal', birthDate: '03/07/2001', ssnr: '0000', email: 'nik#gmail.com', telephoneNumber: '6641234123', street: 'Abcd', zipCode: '6020', city: 'Tyrol');
},
build: () => ClientBloc(authenticationBloc: authenticationBloc),
act: (ClientBloc bloc) => bloc..add(const ClientGetClients(101010)),
expect: () => <dynamic>[
const ClientLoadInProgress(),
],
);
});
});
}
Client_bloc.dart
Future<void> _onGetClients(ClientGetClients event, Emitter<ClientState> emit) async {
// Skip double loadings
if (state is ClientLoadInProgress) return;
PrivateClientModelList _pcml = PrivateClientModelList(<PrivateClientModel>[]);
final PrivateRedeemModel _prm = PrivateRedeemModel(customerId: event.userId, clients: <RedeemClient>[]);
if (state is ClientLoadSuccess) {
final ClientLoadSuccess _currentState = state as ClientLoadSuccess;
_pcml = _currentState.pcml;
try {
emit(const ClientLoadInProgress());
_pcml = await _clientRepository.getClientsForUser(event.userId);
} catch (e) {
final KBMException _exception = e as KBMException;
emit(ClientLoadFailure(exception: _exception));
}
return emit(_currentState.copyWith(pcml: _pcml));
} else {
try {
emit(const ClientLoadInProgress());
_pcml = await _clientRepository.getClientsForUser(event.userId);
for (final PrivateClientModel _client in _pcml.data) {
_prm.clients.add(RedeemClient(clientId: _client.id, quantity: 0));
}
} catch (e) {
final KBMException _exception = e as KBMException;
emit(ClientLoadFailure(exception: _exception));
}
return emit(ClientLoadSuccess(_pcml, _prm));
}
}
In the above code when 'getClientsForUser' is being called the response is null.

I need to print a variable from another class

hi everyone I need to print a variables from another class which are they bannerImageUrl and the profileImageUrl I saved them to the firebase storage and it is appears to the folders there but I want to print their url in one of the collection in the firebasefirestore .
this the UtilsService to upload the images to database
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
class UtilsService {
Future<String> uploadFile(File _image, String path) async {
// refrence to upload an img
firebase_storage.Reference storageReference =
firebase_storage.FirebaseStorage.instance.ref(path);
firebase_storage.UploadTask uploadTask = storageReference.putFile(_image);
await uploadTask.whenComplete(() => null);
String returnURL = '';
await storageReference.getDownloadURL().then((fileURL) {
returnURL = fileURL;
});
return returnURL;
}
}
and this the UserService to save the images into the data base
import 'dart:collection';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:insight_software/models/user.dart';
import 'package:insight_software/other_screen/UtlsService.dart';
class UserService {
UtilsService _utilsService = UtilsService();
List<UserModel?> _userListFromQuerySnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return UserModel(
id: doc.id,
name: doc.get("First Name:"),
profileImageUrl: doc.get('profileImageUrl') ?? '',
bannerImageUrl: doc.get('bannerImageUrl') ?? '',
email: doc.get('email') ?? '',
);
}).toList();
}
UserModel? _userFromFirebaseSnapshot(DocumentSnapshot snapshot) {
return snapshot != null
? UserModel(
id: snapshot.id,
name: snapshot.get("First Name:"),
profileImageUrl: snapshot.get('profileImageUrl'),
bannerImageUrl: snapshot.get('bannerImageUrl'),
email: snapshot.get('email'),
)
: null;
}
Stream<UserModel?> getUserInfo(uid) {
return FirebaseFirestore.instance
.collection("Users")
.doc(uid)
.snapshots()
.map(_userFromFirebaseSnapshot);
}
// save the images into the database
Future<void> updateprofile(
File _bannerImage, File _profileImage, String name) async {
// track for the banner image and the profile image
String bannerImageUrl = '';
String profileImageUrl = '';
if (_bannerImage != null) {
bannerImageUrl = await _utilsService.uploadFile(_bannerImage,
'Users/profile/${FirebaseAuth.instance.currentUser!.uid}/banner');
}
if (_profileImage != null) {
profileImageUrl = await _utilsService.uploadFile(_profileImage,
'Users/profile/${FirebaseAuth.instance.currentUser!.uid}/profileimg');
}
// UPLOADING THE BANNER IMAGE AND PROFILE IMAGE AND THE NAME TO DATABASE
Map<String, Object> data = new HashMap();
if (name != '') data['First Name'] = name;
if (bannerImageUrl != '') data['bannerImageUrl'] = bannerImageUrl;
if (profileImageUrl != '') data['profileImageUrl'] = profileImageUrl;
await FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser!.uid)
.update(data);
}
}
and the class that I want to print the variables URL is SignUppage2 it is too long but I will provide the part that I want to call the variables in
child: MaterialButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
Users.add({
'First Name': Fname,
'Last Name': Lname,
'user role ': value,
'user gender': value2,
'Nationality': value3,
'intersted Displiance': value4,
'intersted university': value5,
'email': _signupscr!.auth.currentUser?.email,
'bannerImageUrl': _userModel.bannerImageUrl,
'profileImageUrl': _userModel.profileImageUrl,
}).then((value) => print('user added')).catchError(
(error) => print('failed to add user:$error'));
Navigator.of(context).pushNamed('sign up new account');
} else {
print("sign up failed");
}
},
how I can print the bannerImageURL and the profileImageurl in the SignUppage2??
what i add in the class it is print an empty string in the Firestore
You can use argument parameter to pass data to another screen.
Navigator.pushNamed(context, "sign up new account",arguments: {"bannerImageURL " :
_userModel.bannerImageUrl, "profileImageUrl": _userModel.profileImageUrl});
},
And on SignUpPage2 you can get data in build method get as:
#override
Widget build(BuildContext context) {
final Map<String, Object>rcvdData = ModalRoute.of(context).settings.arguments;
print("rcvd fdata ${rcvdData['profileImageUrl']}");
print("rcvd fdata ${rcvdData['bannerImageURL ']}");
return Scaffold(appBar: AppBar(title: Text("Second")),
body: Container(child: Column(children: <Widget>[
Text("Second"),
],),),);
}