Im doing an integration test in Flutter and in the application I open the camera, but I don't know how to tap on the button to do the photo, anyone know how can I search for this button?
Here is the code if the app where you can choose between pic a photo with the camera or choose one picture of your gallery
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import 'package:random_string/random_string.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:rosita/language/firebase_remote.dart';
import 'package:rosita/api/api_provider.dart';
import 'package:rosita/constants/common.dart';
import 'package:rosita/model/image_object.dart';
import 'package:rosita/model/senior_user.dart';
import 'package:rosita/modules/widgets/button_ui.dart';
import 'package:rosita/rosita.dart';
class AddProfileImageScreen extends StatefulWidget {
const AddProfileImageScreen({Key key, this.seniorUser}) : super(key: key);
final SeniorUser seniorUser;
#override
_AddProfileImageScreenState createState() => _AddProfileImageScreenState();
}
class _AddProfileImageScreenState extends State<AddProfileImageScreen> {
bool _isProcessing = false;
File _image;
bool _enableButton = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: ModalProgressHUD(
inAsyncCall: _isProcessing,
color: Colors.transparent,
progressIndicator: const CircularProgressIndicator(
strokeWidth: 2.0,
),
child: Container(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height,
minWidth: MediaQuery.of(context).size.width),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
darkSubtitleText('choose_profile_picture', context),
Expanded(
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: Card(
shape: RoundedRectangleBorder(
side: const BorderSide(
color: AppTheme.purpleColor,
width: 4,
),
borderRadius: BorderRadius.circular(60.0),
),
elevation: 0,
color: Theme.of(context).dividerColor,
child: _image == null
? (widget.seniorUser != null &&
widget.seniorUser.profileImage != null &&
widget.seniorUser.profileImage.imageUrl !=
'')
? CachedNetworkImage(
imageUrl:
widget.seniorUser.profileImage.imageUrl,
placeholder:
(BuildContext context, String url) =>
Image.asset(ConstantsData.appIcon),
errorWidget: (BuildContext context,
String url, error) =>
const Icon(Icons.error),
fit: BoxFit.cover,
)
: Image.asset(ConstantsData.appIcon)
: Image.file(_image),
),
),
),
),
ButtonUI(
buttonName: 'ProfilePhotoFromCameraButton',
key: const Key(Keys.cameraButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('take_a_photo_with_your_camera'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: false);
},
),
verticalSpacer(),
ButtonUI(
buttonName: 'ProfilePhotoFromGalleryButton',
key: const Key(Keys.galleryButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('choose_from_gallery'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: true);
},
),
verticalSpacer(),
if (_image != null || _enableButton)
ButtonUI(
buttonName: 'ProfilePhotoUploadButton',
key: const Key(Keys.uploadButton),
isTrack: true,
color: AppTheme.purpleColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('continue_txt'),
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
_uploadAllInformation();
},
),
],
),
),
),
),
);
}
Future<void> getImage({bool isGallery = true}) async {
await <Permission>[Permission.camera, Permission.storage].request();
if (await Permission.storage.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
if (!isGallery &&
await Permission.camera.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
final image = await ImagePicker.pickImage(
source: isGallery ? ImageSource.gallery : ImageSource.camera);
if (image == null) return;
final cropimage = await cropImage(image);
if (cropimage == null) return;
setState(() {
_image = cropimage;
});
}
Future<File> cropImage(File imageFile) async {
final croppedFile = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
statusBarColor: Theme.of(context).primaryColor,
toolbarColor: Theme.of(context).primaryColor,
toolbarWidgetColor: Theme.of(context).backgroundColor,
),
sourcePath: imageFile.path,
cropStyle: CropStyle.circle,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
maxWidth: 420,
maxHeight: 420,
);
return croppedFile;
}
Future<void> _uploadAllInformation() async {
setState(() {
_isProcessing = true;
});
widget.seniorUser.documentId =
(await FirebaseAuth.instance.currentUser()).uid;
widget.seniorUser.referralCode =
'RO-' + randomAlphaNumeric(8).toUpperCase();
widget.seniorUser.enterReferralCode = deepLinkReferralCode;
await ApiProvider().createSeniorUserProfile(widget.seniorUser);
endRegister = true;
if (!_enableButton) {
final imageData = await updateProfilePic(widget.seniorUser);
await ApiProvider()
.updateRositaProfileImage(imageData, widget.seniorUser.documentId);
}
setState(() {
_isProcessing = false;
});
Rosita.restartApp(context);
}
Future<ImageObject> updateProfilePic(SeniorUser user) async {
final imagename = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg';
final url = await ApiProvider()
.updateProfilePic('rositapics/${user.documentId}/' + imagename, _image);
final profileImage = ImageObject();
profileImage.imageUrl = url.toString();
profileImage.firebaseStoregPath =
'rositapics/${user.documentId}/' + imagename;
profileImage.imageName = imagename;
return profileImage;
}
}
Related
I need to delete the users profile from firebase, thing is I have 3 collections petfiles, petsdetails and users which need to be deleted. As in when a user signs up, they can create a pet and create records for their pet. But when having to delete the user, it should delete all the pets and records the pet has (it could be up to any amount)
I havent tried anything as I dont really know how to solve this but this is my code
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vet_bookr/oScreens/petFiles.dart';
import '../constant.dart';
class UserDetails extends StatefulWidget {
UserDetails({Key? key, required this.details}) : super(key: key);
Map<String, dynamic> details;
#override
State<UserDetails> createState() => _UserDetailsState();
}
class _UserDetailsState extends State<UserDetails> {
List<String> labels = ["Email", "Phone Number"];
bool editableText = false;
String imageUrl = "";
List<String> petIds = [];
#override
void initState() {
// TODO: implement initState
nameController.text = widget.details["name"];
ageController.text = widget.details["age"];
super.initState();
}
Future<void> uploadImages({required String path}) async {
try {
final imageRef = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await imageRef.putFile(File(path));
imageUrl = await imageRef.getDownloadURL();
setState(() {});
//print(imageRef.getDownloadURL());
} on FirebaseException catch (e) {
print("Function does work");
SnackBar snackBar = SnackBar(content: Text(e.message!));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
bool isLoading = false;
final nameController = TextEditingController();
final ageController = TextEditingController();
XFile? profilePic;
ImagePicker imagePicker = ImagePicker();
final storageRef = FirebaseStorage.instance.ref();
TextEditingController controllerChanger(index) {
if (index == 0) {
return nameController;
}
if (index == 1) {
return ageController;
}
return TextEditingController();
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
appBar: AppBar(
systemOverlayStyle: SystemUiOverlayStyle.dark,
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.pop(context);
},
),
actions: [
Padding(
padding: EdgeInsets.only(right: 5.sp),
child: PopupMenuButton(
icon: Icon(
Icons.more_vert,
color: Colors.black,
),
itemBuilder: (context) {
return [
PopupMenuItem<int>(
value: 0,
child: Text("Edit Profile"),
),
PopupMenuItem<int>(
value: 1,
child: Text("Delete Profile"),
),
];
},
onSelected: (value) async {
if (value == 0) {
setState(() {
editableText = true;
});
print(editableText);
} else if (value == 1) {
setState(() {
isLoading = true;
});
final ref = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await ref.delete();
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.delete();
DocumentSnapshot<Map<dynamic, dynamic>> snap =
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.get();
await FirebaseFirestore.instance
.collection("petDetails")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!),
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayUnion(snap.data()!["pets"]!),
});
setState(() {
isLoading = false;
});
Navigator.pop(context);
}
},
))
],
),
extendBodyBehindAppBar: true,
backgroundColor: kBackgroundColor,
body: isLoading
? Container(
width: 1.sw,
height: 0.4.sh,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 15.sp,
width: 15.sp,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Color(0xffFF8B6A),
),
),
],
),
)
: SafeArea(
child: Container(
//alignment: Alignment.center,
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(15.sp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// sBox(h: 10),
Text(
'Pet Information',
style: TextStyle(
color: Color(0xffF08519), fontSize: 0.05.sw),
),
// myPetTile()
SizedBox(
height: 0.05.sh,
),
Stack(
children: [
CircleAvatar(
radius: 0.095.sh,
backgroundColor: Color(0xffFF8B6A),
backgroundImage: profilePic == null
? NetworkImage(
widget.details["profilePicture"],
)
: null,
child: profilePic == null
? Container(
width: 0,
height: 0,
)
: ClipRRect(
borderRadius:
BorderRadius.circular(100),
child: Image.file(
File(
"${profilePic?.path}",
),
),
),
),
editableText
? Positioned(
right: 0.025.sw,
bottom: 0.005.sh,
child: GestureDetector(
onTap: () async {
profilePic = await ImagePicker()
.pickImage(
source: ImageSource.gallery);
setState(() {});
},
child: CircleAvatar(
backgroundColor: Color(0xffFF8B6A),
radius: 0.02.sh,
child: Icon(
Icons.camera_alt_outlined,
size: 0.05.sw,
color: Colors.white,
),
),
),
)
: Container(
width: 0,
height: 0,
)
],
),
SizedBox(
height: 0.02.sh,
),
...List.generate(
2,
(index) => Padding(
padding: EdgeInsets.only(
top: 0.02.sh, left: 0.05.sw, right: 0.05.sw),
child: TextField(
enabled: editableText,
controller: controllerChanger(index),
style: TextStyle(fontSize: 0.017.sh),
cursorColor: Colors.black,
decoration: InputDecoration(
label: Text(labels[index],
style: TextStyle(fontSize: 0.02.sh)),
labelStyle: TextStyle(color: Colors.black54),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.sp),
borderSide:
BorderSide(color: Color(0xffFF8B6A))),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.sp),
),
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.sp),
borderSide:
BorderSide(color: Color(0xffFF8B6A))),
contentPadding:
EdgeInsets.symmetric(horizontal: 10.sp),
hintStyle: TextStyle(color: Colors.grey),
),
),
),
),
buttonWidget()
],
),
),
),
),
),
),
);
}
bool isLoadingEdit = false;
Widget buttonWidget() {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 0.4.sw,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
backgroundColor: Color(0xffFF8B6A),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.sp),
),
),
onPressed: () async {
if (editableText) {
setState(() {
isLoadingEdit = true;
});
if (profilePic != null) {
final ref = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await ref.delete();
await uploadImages(path: profilePic!.path);
}
await FirebaseFirestore.instance
.collection("petsDetails")
.doc(widget.details["id"])
.update({
'name': nameController.text,
'age': ageController.text,
'breed': breedController.text,
'weight': weightController.text,
'profilePicture': profilePic != null
? imageUrl
: widget.details["profilePicture"],
'lastVaccinationDate':
widget.details["lastVaccinationDate"]
});
DocumentSnapshot<Map<String, dynamic>> snap =
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.get();
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!)
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!),
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayUnion(snap.data()!["pets"]!),
});
Navigator.pop(context);
setState(() {
isLoadingEdit = false;
editableText = false;
});
const snackBar = SnackBar(
content: Text("Your pet's details have been changed"),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PetFiles(
petId: widget.details["id"],
),
),
);
}
},
child: isLoadingEdit
? Container(
height: 15.sp,
width: 15.sp,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2.sp,
),
)
: Text(
editableText ? "Save Changes" : "Pet Health Records",
style:
TextStyle(color: Colors.white, fontSize: 0.03.sw),
),
),
),
],
),
SizedBox(
height: 0.01.sh,
),
],
);
}
}
You can check out their official docs for deleting collections here.
Or you can upgrade your project to blaze plan and use this extension which takes care of it for you.
Alternatively you can use NodeJS and FirebaseFunctions to do this task for you. Use this code snippet
async function deleteCollection(db, collectionPath, batchSize) {
const collectionRef = db.collection(collectionPath);
const query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject);
});
}
async function deleteQueryBatch(db, query, resolve) {
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve();
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, resolve);
});
}
index.js
I am trying to build a image picker using flutter. I want the user to be able to select an image and upload it onto firebase storage so that it can be later retrieved. I am using an image picker to select the image from the gallery and I am then setting the image selected as a file. I am then creating a reference called firebaseStorageRef and using firebaseStorageRef.putFile(_selectedImage!) to upload the data.
However, I am getting the error:
Restarted application in 553ms.
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_storage/object-not-found] No object exists at the desired reference.
main.dart:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blog/views/homePage.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: "Blog App",
themeMode: ThemeMode.dark,
debugShowCheckedModeBanner: false,
home: homePage());
}
}
create_blog.dart code:
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blog/services/crud.dart';
import 'package:image_picker/image_picker.dart';
import 'package:random_string/random_string.dart';
import 'package:firebase_core/firebase_core.dart';
class CreateBlog extends StatefulWidget {
const CreateBlog({super.key});
#override
State<CreateBlog> createState() => _CreateBlogState();
}
class _CreateBlogState extends State<CreateBlog> {
late String authorName, title, desc;
bool isloading = false;
CRUDMethods crudMethods = new CRUDMethods();
File? _selectedImage;
Future getImage() async {
var image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final image_path = File(image.path);
setState(() {
_selectedImage = image_path;
});
}
uploadBlog() async {
if (_selectedImage != null) {
// Uploading image to Firestore
setState(() {
isloading = true;
});
var firebaseStorageRef = FirebaseStorage.instance
.ref()
.child("blogImages")
.child("${randomAlphaNumeric(9)}.jpg");
try {
var task = firebaseStorageRef
.putFile(_selectedImage!)
.whenComplete(() => Navigator.pop(context));
} catch (error) {
print(error);
}
} else {}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
Text(
"Flutter",
style: TextStyle(
fontSize: 22,
color: Colors.black,
),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
]),
backgroundColor: Colors.transparent,
elevation: 0,
actions: <Widget>[
GestureDetector(
onTap: () {
uploadBlog();
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Icon(
Icons.file_upload,
color: Colors.black,
)))
],
),
backgroundColor: Colors.white,
body: isloading
? Container(
alignment: Alignment.center,
child: CircularProgressIndicator(color: Colors.teal),
)
: Container(
child: Column(
children: <Widget>[
SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
getImage();
},
child: _selectedImage != null
? Container(
margin: EdgeInsets.symmetric(horizontal: 30),
height: 150,
width: MediaQuery.of(context).size.width,
child: Image.file(
_selectedImage!,
fit: BoxFit.cover,
),
)
: Container(
margin: EdgeInsets.symmetric(horizontal: 30),
height: 150,
width: MediaQuery.of(context).size.width,
child: Icon(Icons.add_a_photo),
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(6)),
),
),
SizedBox(
height: 8,
),
Container(
margin: EdgeInsets.symmetric(horizontal: 30),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: "Author Name"),
onChanged: (val) {
authorName = val;
},
),
TextField(
decoration: InputDecoration(hintText: "Title"),
onChanged: (val) {
title = val;
},
),
TextField(
decoration: InputDecoration(hintText: "Description"),
onChanged: (val) {
desc = val;
},
)
],
),
)
],
)),
);
}
}
crud.dart code:
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class CRUDMethods {
Future<void> addData(blogData) async {
FirebaseFirestore.instance
.collection("blogs")
.add(blogData)
.catchError((e) {
print(e);
});
}
}
This is a Flutter app that I wrote long ago which pushes a user-selected image to Firebase and generates output using an ML model on the server.
I want to modify the same app. It is a completely offline app, so Firebase is not an option. So there are just 4 images that the user will be using as input. The app must be hardcoded to display a predefined output depending on which image is uploaded.
The possible methods I thought of were,
Store those images as assets in the app. Compare the input image's name to that of the asset images. Display output is there is a match.
Use image comparison algorithms using packages like image_compare.
None of the above methods worked, maybe I am doing it wrong. Please help me out.
Also, sorry for the non systematic code below.
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:del04/splashscreen.dart';
import 'package:del04/page/info_page.dart';
import 'package:del04/data.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:iconsax/iconsax.dart';
import 'package:path/path.dart';
import 'package:file_picker/file_picker.dart';
import 'package:file_support/file_support.dart';
late String name, path , domain , phylum , clas , order , family , genus , species ;
File? _photo;
// ignore: prefer_typing_uninitialized_variables
var image;
File a= File('assets/images/1.jpg'), b= File('assets/images/2.jpg'), c= File('assets/images/3.jpg'), d= File('assets/images/4.jpg');
var which=-1;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const Splash_screen(),
'/home': (context) => ImageUploads(),
'/home/info_page': (context) => Info_page()
}
)
);
}
class ImageUploads extends StatefulWidget {
const ImageUploads({Key? key}) : super(key: key);
#override
// ignore: library_private_types_in_public_api
_ImageUploadsState createState() => _ImageUploadsState();
}
class _ImageUploadsState extends State<ImageUploads> {
//firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;
Future imgFromGallery() async {
final FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'pdf'],
);
setState(() {
if (result != null) {
_photo= result as File;
String? filename= FileSupport().getFileNameWithoutExtension(_photo!);
image= _photo as Image;
} else {
if (kDebugMode) {
print('No image selected.');
}
}
});
}
/* Future imgFromCamera() async {
final pickedFile = await _picker.pickImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_photo = File(pickedFile.path);
image= _photo;
} else {
// ignore: avoid_print
print('No image selected.');
}
});
} //from Camera
Future uploadFile() async {
//if (_photo == null) return;
//const destination = 'Abhinav/';
try {
final ref = firebase_storage.FirebaseStorage.instance
.ref(destination)
.child('file/');
await ref.putFile(_photo!);
}
catch (e) {
if (kDebugMode) {
print('Error occurred, try again.');
}
}
}*/
void _onLoading() {
/*showDialog(
context: this.context,
barrierDismissible: false,
builder: (BuildContext context) {
return Dialog(
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
SizedBox(height: 80, width: 80),
CircularProgressIndicator(),
Text(" Analyzing..."),
],
),
);
},
);*/
//douploadingshit();
Future.delayed(const Duration(seconds: 2), () async {
if(image.readAsBytesSync().lengthInBytes != a.readAsBytesSync().lengthInBytes)which= 1;
else if(image.readAsBytesSync().lengthInBytes == b.readAsBytesSync().lengthInBytes)which= 2;
else if(image.readAsBytesSync().lengthInBytes == c.readAsBytesSync().lengthInBytes)which= 3;
else if(image.readAsBytesSync().lengthInBytes == d.readAsBytesSync().lengthInBytes)which= 4;
else which= 99;
//pop dialog
//final ref = FirebaseDatabase.instance.ref();
//final snapshot = await ref.child('/').get();
//name = (snapshot.value) as String;
const Data().setData();
//Navigator.pop(this.context); //pop dialog
Navigator.of(this.context).push(MaterialPageRoute(builder: (context)=>Info_page()));
/*if(which==99){
fetch_errorM();
}
else{
Navigator.of(this.context).push(MaterialPageRoute(builder: (context)=>Info_page()));
}*/
});
}
/* Future<void> douploadingshit() async {
uploadFile();
DatabaseReference ref = FirebaseDatabase.instance.ref("");
await ref.update({
"confirm/state": "yes",
});
}*/
void fetch_errorM() {
showDialog(
context: this.context,
barrierDismissible: false,
builder: (BuildContext context) {
return Dialog(
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
SizedBox(height: 80, width: 30),
Text("Could not analyze sample.\nPlease Retry or try another Image."),
],
),
);
},
);
Future.delayed(const Duration(seconds: 2), () async {
Navigator.pop(this.context); //pop dialog
});
}
//----------------------------------------------------------------------------
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('\t Baclens'),
backgroundColor: Colors.blueGrey.shade900,
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
const SizedBox(height: 80,),
Text('Upload your image file', style: TextStyle(fontSize: 25, color: Colors.grey.shade800, fontWeight: FontWeight.bold),),
const SizedBox(height: 10,),
Text('File should be jpg or png only', style: TextStyle(fontSize: 15, color: Colors.grey.shade500),),
const SizedBox(height: 20,),
GestureDetector(
onTap: () {
_showPicker(context);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0, vertical: 20.0),
child: DottedBorder(
borderType: BorderType.RRect,
radius: const Radius.circular(10),
dashPattern: const [10, 5],
strokeCap: StrokeCap.round,
color: Colors.grey.shade900,
child: Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
color: Colors.blue.shade50.withOpacity(.3),
borderRadius: BorderRadius.circular(10)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Iconsax.document_upload5, color: Colors.grey.shade900, size: 40,),
const SizedBox(height: 15,),
Text('Click to choose image', style: TextStyle(fontSize: 15, color: Colors.grey.shade400),),
],
),
),
)
),
),
_photo != null
? Container(
padding: const EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(' Selected File:',
style: TextStyle(color: Colors.grey.shade400, fontSize: 15, ),),
const SizedBox(height:10),
Container(
padding: const EdgeInsets.all(5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(1),
color: Colors.transparent,
),
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: Image.file(_photo!, width: 200, height: 200, fit: BoxFit.fitWidth)
),
)
),
const SizedBox(height: 30,),
MaterialButton(
minWidth: double.infinity,
height: 50,
onPressed: () {
_onLoading();
////////////////////////////////////////////////////////////////////////////////
setState((){
const Data().setData();
Navigator.pop(this.context); //pop dialog
Navigator.of(this.context).push(MaterialPageRoute(builder: (context)=>Info_page()));
});
},
color: Colors.blueGrey.shade900,
child: const Text('Upload', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),),
)
],
))
: Container(),
const SizedBox(height: 150,),
],
),
),
);
}
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Wrap(
children: <Widget>[
ListTile(
leading: const Icon(Icons.photo_library),
title: const Text('Gallery'),
onTap: () {
imgFromGallery();
Navigator.of(context).pop();
}),
/*ListTile(
leading: const Icon(Icons.photo_camera),
title: const Text('Camera'),
onTap: () {
imgFromCamera();
Navigator.of(context).pop();
},
),*/
],
),
);
});
}
}
If I understood correctly (but clearly I don't) when you need a var available when you build the widget you need to call the function in the initState(). The function is 'void getDevices()'
I need var _documentsIds to build DropdownMenuItem.
var _documentsIds is docs ID from a query I make to FirebaseFirestore
How do I make _documentsIds available to be used in my Widget?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:safegaurd/constants.dart';
import 'package:flutter_time_picker_spinner/flutter_time_picker_spinner.dart';
import 'package:safegaurd/screens/log_in_page.dart';
import 'package:safegaurd/components/buttons_navigate.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'new_device_page.dart';
class DeviceSelectionPage extends StatefulWidget {
const DeviceSelectionPage({Key? key}) : super(key: key);
static const String id = 'device_selection_page';
#override
State<DeviceSelectionPage> createState() => _DeviceSelectionPageState();
}
class _DeviceSelectionPageState extends State<DeviceSelectionPage> {
final _auth = FirebaseAuth.instance;
User? loggedInUser;
final firestoreInstance = FirebaseFirestore.instance;
final String devices = 'devices';
List? _documentsIds;
bool showSpinner = false;
String? selectedValue;
final bool checkOne = false;
Color sDeviceAlways = Colors.white54;
Color sDeviceTime = Colors.white54;
FontWeight sDeviceAlwaysW = FontWeight.normal;
FontWeight sDeviceTimeW = FontWeight.normal;
#override
void initState() {
super.initState();
getCurrentUser();
getDevices();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
getDevices();
};
} catch (e) {
print(e);
}
}
void getDevices() async {
var firebaseUser = FirebaseAuth.instance.currentUser?.email;
print('firebaseUser: $firebaseUser');
var query = await firestoreInstance
.collection(devices)
.where('email', isEqualTo: '$firebaseUser')
.get();
var _documentsIds = query.docs.map((doc) => doc.id).toList();
print('_documentsIds: $_documentsIds');
}
#override
Widget build(BuildContext context) {
print('_documentsIds: $_documentsIds');
return Scaffold(
appBar: AppBar(
leading: null,
actions: [
IconButton(
onPressed: () {
_auth.signOut();
Navigator.pop(context);
},
icon: Icon(Icons.close))
],
title: const Text('Device Selection page'),
),
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
child: Text(
'SAFEGAURD',
style: kAppTextStyle,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 380,
padding: const EdgeInsets.symmetric(horizontal: 24.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.lightBlueAccent, width: 1.0),
borderRadius: kBorderRadius),
child: DropdownButtonHideUnderline(
child: DropdownButton(
hint: const Text(
'Safegaurd Devices',
style: TextStyle(color: Colors.white54, fontSize: 25),
),
style:
const TextStyle(color: Colors.orange, fontSize: 25),
borderRadius: kBorderRadius,
iconSize: 40,
elevation: 16,
onChanged: (value) {
setState(() {
selectedValue = value.toString();
setState(() {
selectedValue;
print(selectedValue);
});
});
},
value: selectedValue,
items: _documentsIds?.map((itemsList) {
return DropdownMenuItem<String>(
value: itemsList,
child: Text(itemsList),
);
}).toList(),
),
),
)
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Save Settings',
onPressed: () {},
width: 200,
),
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Claim new Device',
onPressed: () {
Navigator.pushNamed(context, NewDevicePage.id);
},
width: 200,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Buttons_Navigate(
colour: Colors.orange,
title: 'Back',
onPressed: () {
Navigator.pushNamed(context, LogInPage.id);
},
width: 40)
],
)
],
)),
));
}
}
wall, you can use futureBuilder and show A CircularProgressBar until the query is done check the documentation here: FutureBuilder
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:safegaurd/constants.dart';
//import 'package:flutter_time_picker_spinner/flutter_time_picker_spinner.dart';
import 'package:safegaurd/screens/log_in_page.dart';
import 'package:safegaurd/components/buttons_navigate.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'new_device_page.dart';
class DeviceSelectionPage extends StatefulWidget {
const DeviceSelectionPage({Key? key}) : super(key: key);
static const String id = 'device_selection_page';
#override
State<DeviceSelectionPage> createState() => _DeviceSelectionPageState();
}
class _DeviceSelectionPageState extends State<DeviceSelectionPage> {
final _auth = FirebaseAuth.instance;
User? loggedInUser;
final firestoreInstance = FirebaseFirestore.instance;
final String devices = 'devices';
List? _documentsIds;
bool showSpinner = false;
//bool _isSelected1 = false;
//bool _isSelected2 = false;
//DateTime _dateTime = DateTime.now();
String? selectedValue;
final bool checkOne = false;
Color sDeviceAlways = Colors.white54;
Color sDeviceTime = Colors.white54;
FontWeight sDeviceAlwaysW = FontWeight.normal;
FontWeight sDeviceTimeW = FontWeight.normal;
#override
void initState() {
super.initState();
getCurrentUser();
getDevices();
}
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
getDevices();
};
} catch (e) {
print(e);
}
}
Future<List<dynamic>> getDevices() async {
var firebaseUser = FirebaseAuth.instance.currentUser?.email;
print('firebaseUser: $firebaseUser');
var query = await firestoreInstance
.collection(devices)
.where('email', isEqualTo: '$firebaseUser')
.get();
List<String> _documentsIds = query.docs.map((doc) => doc.id).toList();
print('_documentsIds: $_documentsIds');
return _documentsIds;
}
#override
Widget build(BuildContext context) {
print('_documentsIds: $_documentsIds');
return Scaffold(
appBar: AppBar(
leading: null,
actions: [
IconButton(
onPressed: () {
_auth.signOut();
Navigator.pop(context);
},
icon: Icon(Icons.close))
],
title: const Text('Device Selection page'),
),
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(
height: 40,
child: Text(
'SAFEGAURD',
style: kAppTextStyle,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 380,
padding: const EdgeInsets.symmetric(horizontal: 24.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.lightBlueAccent, width: 1.0),
borderRadius: kBorderRadius),
child: DropdownButtonHideUnderline(
child: FutureBuilder<List> (
future: getDevices(),
builder: (BuildContext context, AsyncSnapshot<List> snapshot){
if (!snapshot.hasData) {
return const Text('Waiting Devices',style: TextStyle(color: Colors.white54, fontSize: 25));
} else {
return DropdownButton(
hint: const Text(
'Safegaurd Devices',
style: TextStyle(color: Colors.white54, fontSize: 25),
),
style:
const TextStyle(color: Colors.orange, fontSize: 25),
borderRadius: kBorderRadius,
iconSize: 40,
elevation: 16,
onChanged: (value) {
setState(() {
selectedValue = value.toString();
setState(() {
selectedValue;
print(selectedValue);
});
});
},
value: selectedValue,
items: snapshot.data?.map((_documentsIds) =>
DropdownMenuItem<String>(
value: _documentsIds,
child: Text(_documentsIds),
)
).toList(),
);
}
}
)
),
)
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Save Settings',
onPressed: () {},
width: 200,
),
],
),
Row(
children: [
Buttons_Navigate(
colour: Colors.teal,
title: 'Claim new Device',
onPressed: () {
Navigator.pushNamed(context, NewDevicePage.id);
},
width: 200,
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Buttons_Navigate(
colour: Colors.orange,
title: 'Back',
onPressed: () {
Navigator.pushNamed(context, LogInPage.id);
},
width: 40)
],
)
],
)),
));
}
This is a simple flutter app. I am getting this error on my signup page which connects to firebase.
when i try to sign up, it remains on thinking with ⭕ spinning, i am getting this error in the debug console:
VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: Null check operator used on a null value
#0 _SignupScreenState.signUpUser package:instagram_flutter/screens/signup_screen.dart:5
any thoughts?
here is the code that I believe is the source of the problem at:
(_image != null
? CircleAvatar
This is that block of code:
Stack(
children: [
_image != null
? CircleAvatar(
radius: 32,
backgroundImage: MemoryImage(_image!),
backgroundColor: Colors.red,
)
: const CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
),
I am new to coding and flutter, what should I put to replace the "?"
here is the entire code for the sign_up_screen (it is taken from a tutorial):
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:instagram_flutter/resources/auth_methods.dart';
import 'package:instagram_flutter/responsive/mobile_screen_layout.dart';
import 'package:instagram_flutter/responsive/web_screen_layout.dart';
import 'package:instagram_flutter/screens/login_screen.dart';
import 'package:instagram_flutter/utils/colors.dart';
import 'package:instagram_flutter/utils/utils.dart';
import '../responsive/responsive_layout_screen.dart';
import '../widgets/text_field_input.dart';
class SignupScreen extends StatefulWidget {
const SignupScreen({Key? key}) : super(key: key);
#override
_SignupScreenState createState() => _SignupScreenState();
}
class _SignupScreenState extends State<SignupScreen> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _bioController = TextEditingController();
bool _isLoading = false;
Uint8List? _image;
#override
void dispose() {
super.dispose();
_emailController.dispose();
_passwordController.dispose();
_usernameController.dispose();
}
void signUpUser() async {
// set loading to true
setState(() {
_isLoading = true;
});
// signup user using our authmethodds
String res = await AuthMethods().signUpUser(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
bio: _bioController.text,
file: _image!);
// if string returned is sucess, user has been created
if (res == "success") {
setState(() {
_isLoading = false;
});
// navigate to the home screen
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const ResponsiveLayout(
mobileScreenLayout: MobileScreenLayout(),
webScreenLayout: WebScreenLayout(),
),
),
);
} else {
setState(() {
_isLoading = false;
});
// show the error
showSnackBar(context, res);
}
}
selectImage() async {
Uint8List im = await pickImage(ImageSource.gallery);
// set state because we need to display the image we selected on the circle avatar
setState(() {
_image = im;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 32),
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
child: Container(),
flex: 2,
),
SvgPicture.asset(
'assets/ic_instagram.svg',
color: primaryColor,
height: 64,
),
const SizedBox(
height: 64,
),
Stack(
children: [
_image != null
? CircleAvatar(
radius: 64,
backgroundImage: MemoryImage(_image!),
backgroundColor: Colors.red,
)
: const CircleAvatar(
radius: 64,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
),
Positioned(
bottom: -10,
left: 80,
child: IconButton(
onPressed: selectImage,
icon: const Icon(Icons.add_a_photo),
),
)
],
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your username',
textInputType: TextInputType.text,
textEditingController: _usernameController,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your email',
textInputType: TextInputType.emailAddress,
textEditingController: _emailController,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your password',
textInputType: TextInputType.text,
textEditingController: _passwordController,
isPass: true,
),
const SizedBox(
height: 24,
),
TextFieldInput(
hintText: 'Enter your bio',
textInputType: TextInputType.text,
textEditingController: _bioController,
),
const SizedBox(
height: 24,
),
InkWell(
child: Container(
child: !_isLoading
? const Text(
'Sign up',
)
: const CircularProgressIndicator(
color: primaryColor,
),
width: double.infinity,
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: const ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4)),
),
color: blueColor,
),
),
onTap: signUpUser,
),
const SizedBox(
height: 12,
),
Flexible(
child: Container(),
flex: 2,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: const Text(
'Already have an account?',
),
padding: const EdgeInsets.symmetric(vertical: 8),
),
GestureDetector(
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LoginScreen(),
),
),
child: Container(
child: const Text(
' Login.',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
padding: const EdgeInsets.symmetric(vertical: 8),
),
),
],
),
],
),
),
),
);
}
}
there is also the auth page, which includes a warning regarding
file != null) {:
the warning says:
The operand can't be null, so the condition is always true.
Remove the condition.dartunnecessary_null_comparison
auth_methods.dart:
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:instagram_flutter/resources/storage_methods.dart';
class AuthMethods {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
//sign up user
Future<String> signUpUser({
required String email,
required String password,
required String username,
required String bio,
required Uint8List file,
}) async {
String res = "Some error Occurred";
try {
if (email.isNotEmpty ||
password.isNotEmpty ||
username.isNotEmpty ||
bio.isNotEmpty ||
file != null) {
// registering user in auth with email and password
UserCredential cred = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
String photoUrl = await StorageMethods()
.uploadImageToStorage('profilePics', file, false);
await _firestore.collection('users').doc(cred.user!.uid).set({
'username': username,
'uid': cred.user!.uid,
'email': email,
'bio': bio,
'followers': [],
'following': [],
'photoUrl': photoUrl,
});
res = "success";
} else {
res = "Please enter all the fields";
}
} catch (err) {
return err.toString();
}
return res;
}
// logging in user
Future<String> loginUser({
required String email,
required String password,
}) async {
String res = "Some error Occurred";
try {
if (email.isNotEmpty || password.isNotEmpty) {
// logging in user with email and password
await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
res = "success";
} else {
res = "Please enter all the fields";
}
} catch (err) {
return err.toString();
}
return res;
}
Future<void> signOut() async {
await _auth.signOut();
}
}
Make sure that the declaration for _image is of type MemoryImage like this: MemoryImage? _image; Then, when using the value for the background image, just use _image, not MemoryImage(_image!).
Try using this way..
Stack(
children: [
_image == null
? const CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
'https://i.stack.imgur.com/l60Hf.png'),
backgroundColor: Colors.red,
):
CircleAvatar(
radius: 32,
backgroundImage: MemoryImage(_image),
backgroundColor: Colors.red,
),
On your signUpUser you are directly using bang! without checking null.
Here
// signup user using our authmethodds
...
file: _image!);
Try
void signUpUser() async {
if (_image == null) {
debugPrint("got null on _image");
_isLoading = false;
return;
}
And everything seems ok on Stack