Failed assertion: line 133 pos 12: 'file.absolute.existsSync()': is not true - firebase

Hello I am a beginner and I am trying to record audio and upload it to firebase but I am facing an error which probably says that file does not exists.
Currently Flutter Audio Recorder is reading audio data but when Audio Recorder is set to stop and the process of uploading begins then the error is generated. I have checked file existence using existsSync() method which returned false
Kindly help me out in this. Here is my code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:avatar_glow/avatar_glow.dart';
import 'package:flutter_audio_recorder/flutter_audio_recorder.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path_provider/path_provider.dart';
class HomeView extends StatefulWidget {
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
bool _isRecording;
String _convertedText;
String _fileName;
String _filePath;
FlutterAudioRecorder _audioRecorder;
#override
void initState() {
super.initState();
_isRecording = false;
_fileName = "";
_convertedText = "Press the Record button to convert text";
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Urdu Speech to Text Converter"),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: AvatarGlow(
animate: _isRecording,
glowColor: Theme
.of(context)
.primaryColor,
endRadius: 75.0,
duration: const Duration(milliseconds: 2000),
repeatPauseDuration: const Duration(milliseconds: 100),
repeat: true,
child: FloatingActionButton(
onPressed: _onRecordButtonPressed,
child: Icon(_isRecording ? Icons.mic : Icons.mic_none),
),
),
body: SingleChildScrollView(
reverse: true,
child: Container(
padding: const EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 150.0),
child: Text(_convertedText)
),
),
);
}
Future<void> _uploadFile() async {
FirebaseStorage firebaseStorage = FirebaseStorage.instance;
try {
await firebaseStorage
.ref()
.child(_fileName)
.putFile(File(_filePath));
} catch (error) {
print('Error occured while uplaoding to Firebase ${error.toString()}');
// Scaffold.of(context).showSnackBar(
// SnackBar(
// content: Text('Error occured while uplaoding'),
// ),
// );
}
}
Future<void> _onRecordButtonPressed() async {
if (_isRecording) {
_audioRecorder.stop();
_isRecording = false;
File(_filePath).existsSync() ? _uploadFile() : print("*************** File Doesn't Exists **************");
} else {
_isRecording = true;
await _startRecording();
}
setState(() {});
}
Future<void> _startRecording() async {
final bool hasRecordingPermission =
await FlutterAudioRecorder.hasPermissions;
if (hasRecordingPermission) {
Directory directory = await getApplicationDocumentsDirectory();
String filepath = directory.path +
'/' +
DateTime
.now()
.millisecondsSinceEpoch
.toString() +
'.wav';
_audioRecorder =
FlutterAudioRecorder(filepath, audioFormat: AudioFormat.WAV);
await _audioRecorder.initialized;
_audioRecorder.start();
_filePath = filepath;
_fileName = _filePath.substring(_filePath.lastIndexOf('/') + 1, _filePath.length);
_convertedText = _fileName;
setState(() {});
} else {
print("*************************** No Permissions *****************************");
}
}
}

Related

Execution failed for task ':location:parseDebugLocalResources'

i'm trying to run my project , i have this page where i want to get current location of the user
but i get a message error when i run it
Message error
** Execution failed for task ':location:parseDebugLocalResources'.
Could not resolve all files for configuration ':location:androidApis'.
Failed to transform android.jar to match attributes {artifactType=android-platform-attr, org.gradle.libraryelements=jar, org.gradle.usage=java-runtime}.
> Execution failed for PlatformAttrTransform:
C:\Users\lenovo\AppData\Local\Android\sdk\platforms\android-30\android.jar.
> C:\Users\lenovo\AppData\Local\Android\sdk\platforms\android-30\android.jar **
The code in the page
// ignore_for_file: deprecated_member_use
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:location/location.dart';
import '../rounded_button.dart';
class DemandeList extends StatefulWidget {
#override
_DemandeList createState() => _DemandeList();
}
class _DemandeList extends State<DemandeList>{
late bool _serviceEnabled;
late PermissionStatus _permissionGranted;
LocationData? _userLocation;
Future<void> _getUserLocation() async {
Location location = Location();
// Check if location service is enable
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
// Check if permission is granted
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
final _locationData = await location.getLocation();
setState(() {
_userLocation = _locationData;
});
}
final db = FirebaseFirestore.instance;
String? Key ;
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Listes des demandes"),
centerTitle: true,
),
body: StreamBuilder<QuerySnapshot>(
stream: db.collection('ambulance')
.where("etat", isEqualTo: "en cours")
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else
return ListView(
children: snapshot.data!.docs.map((doc) {
int lng;
int lat;
return Card(
child: ListTile(
trailing: Text("Accepter",
style: TextStyle(
color: Colors.green,fontSize: 15
),
),
title: new Text(doc['id']) ,
subtitle: new Text(doc['etat']),
onTap: () => {
_getUserLocation,
lat = _userLocation?.latitude as int ,
lng = _userLocation?.longitude as int ,
db.collection("position").add({'lat': lat , "lng": lng ,}),
db.collection("ambulance").doc(doc.id).update({"etat": 'Accept' }),
}
),
);
}).toList(),
);
},
),
);
}
}

How to upload image to Firebase Storage and automatically store it in Cloud Firestore?

I'm currently stuck at where I'm trying to upload image to Firestore Storage and automatically store the image URL to Cloud Firestore. I have tried to manually upload the image to Firebase Storage and pasting the image url to Cloud Firestore then retrieving it to show the image in my app and it works. Heres the coding that I have done so far:
models/enter.dart
class Enter {
final String enterId;
final String enter;
final String price;
final String url;
Enter({this.enter, this.price, #required this.enterId, this.url});
factory Enter.fromJson(Map<String, dynamic> json){
return Enter(
enter: json['enter'],
price: json['price'],
url: json['url'],
enterId: json['enterId']
);
}
Map<String,dynamic> toMap(){
return {
'enter':enter,
'price':price,
'url':url,
'enterId':enterId
};
}
}
services/firestore_service2
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:journal_app/src/models/enter.dart';
class FirestoreService2 {
FirebaseFirestore _db = FirebaseFirestore.instance;
//Get Entries
Stream<List<Enter>> getEnter(){
return _db
.collection('enters')
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => Enter.fromJson(doc.data()))
.toList());
}
//Upsert
Future<void> setEnter(Enter enter){
var options = SetOptions(merge:true);
return _db
.collection('enters')
.doc(enter.enterId)
.set(enter.toMap(),options);
}
//Delete
Future<void> removeEnter(String enterId){
return _db
.collection('enters')
.doc(enterId)
.delete();
}
}
provider/enter_provider.dart
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/services/firestore_service2.dart';
import 'package:uuid/uuid.dart';
class EnterProvider with ChangeNotifier {
final firestoreService = FirestoreService2();
String _enter;
String _price;
String _enterId;
String _url;
var uuid = Uuid();
//Getters
String get enter => _enter;
String get price => _price;
String get url => _url;
Stream<List<Enter>> get enters => firestoreService.getEnter();
//Setters
set changeEnter(String enter){
_enter = enter;
notifyListeners();
}
set changePrice(String price){
_price = price;
notifyListeners();
}
set changeUrl(String url){
_url = url;
notifyListeners();
}
//Functions
loadAll(Enter enter){
if (enter != null && price != null){
_enter =enter.enter;
_price =enter.price;
_url=enter.url;
_enterId = enter.enterId;
} else {
_enter = null;
_price = null;
_url = null;
_enterId = null;
}
}
saveEnter(){
if (_enterId == null){
//Add
var newEnter = Enter(enter: _enter, price: _price, url: _url, enterId: uuid.v1());
print(newEnter.enter);
print(newEnter.price);
print(newEnter.url);
firestoreService.setEnter(newEnter);
} else {
//Edit
var updatedEnter = Enter(enter: _enter, price: _price, url: _url, enterId: _enterId);
firestoreService.setEnter(updatedEnter);
}
}
removeEnter(String enterId){
firestoreService.removeEnter(enterId);
}
}
screens/enter.dart where user insert product name, price and image
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/providers/enter_provider.dart';
import 'package:provider/provider.dart';
class EnterScreen extends StatefulWidget {
final Enter enter;
final Enter price;
final Enter category;
EnterScreen({this.enter, this.price, this.category});
#override
_EnterScreenState createState() => _EnterScreenState();
}
class _EnterScreenState extends State<EnterScreen> {
final enterController = TextEditingController();
final enterController2 = TextEditingController();
#override
void dispose() {
enterController.dispose();
enterController2.dispose();
super.dispose();
}
#override
void initState() {
final enterProvider = Provider.of<EnterProvider>(context,listen: false);
if (widget.enter != null){
//Edit
enterController.text = widget.enter.enter;
enterController2.text = widget.enter.price;
enterProvider.loadAll(widget.enter);
enterProvider.loadAll(widget.price);
} else {
//Add
enterProvider.loadAll(null);
}
super.initState();
}
#override
Widget build(BuildContext context) {
final enterProvider = Provider.of<EnterProvider>(context);
return Scaffold(
appBar: AppBar(title: Text('Products')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: [
TextField(
decoration: InputDecoration(
labelText: 'Product Name', border: InputBorder.none,
),
style: TextStyle(color: Colors.black, fontSize: 25),
maxLines: 5,
minLines: 2,
onChanged: (String value) => enterProvider.changeEnter = value,
controller: enterController,
),
TextField(
decoration: InputDecoration(
labelText: 'Product Price', border: InputBorder.none,
),
style: TextStyle(color: Colors.black, fontSize: 25),
maxLines: 5,
minLines: 2,
onChanged: (String value) => enterProvider.changePrice = value,
controller: enterController2,
),
RaisedButton(
color: Theme.of(context).accentColor,
child: Text('Save',style: TextStyle(color: Colors.white, fontSize: 20)),
onPressed: () {
enterProvider.saveEnter();
Navigator.of(context).pop();
},
),
(widget.enter != null) ? RaisedButton(
color: Colors.red,
child: Text('Delete',style: TextStyle(color: Colors.white, fontSize: 20)),
onPressed: () {
enterProvider.removeEnter(widget.enter.enterId);
Navigator.of(context).pop();
},
): Container(),
],
),
),
);
}
}
screens/product.dart where this screen show the product name, price and image in listview
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:journal_app/src/models/enter.dart';
import 'package:journal_app/src/providers/enter_provider.dart';
import 'package:journal_app/src/screens/enter.dart';
import 'package:provider/provider.dart';
class ProductScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
final enterProvider = Provider.of<EnterProvider>(context);
return Scaffold(
appBar: AppBar(
title: Text('Products'),
),
body: StreamBuilder<List<Enter>>(
stream: enterProvider.enters,
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
leading: Image.network(
snapshot.data[index].url,
width: 100,
height: 100,
fit: BoxFit.fitWidth,
),
trailing:
Icon(Icons.edit, color: Theme.of(context).accentColor),
title: Text(
snapshot.data[index].enter, style: TextStyle(fontSize: 25),
),
subtitle: Text(
snapshot.data[index].price,
),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
EnterScreen(enter: snapshot.data[index], price: snapshot.data[index])));
},
);
});
}),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => EnterScreen()));
},
),
);
}
}
The goal is to upload image to Firebase Storage, storing the image url at the same time when uploading new image.
I need advice for this project.
In order to upload image to Firebase Storage & save it in Cloud Firestore, you need to do the following:
Step 1: Get the image that you want to upload
For this, you can use the image_picker package
It will give you a PickedFile object (let's say it pickedFile). Convert this object to a File object by using this code:
final file = File(pickedFile.path);
Step 2: Upload this file to Firebase Storage:
Give the image that you want to upload a unique name.
final imageName = '${DateTime.now().millisecondsSinceEpoch}.png';
Create Firebase Storage Reference:
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('images/$imageName'); // This will create a images directory in Firebase storage & save your image in that directory
Start uploading image:
final uploadTask = firebaseStorageRef.putFile(file);
final taskSnapshot = await uploadTask.onComplete;
Get the image URL:
final _fileURL = await taskSnapshot.ref.getDownloadURL();
Save this image URL in Cloud Firestore.
// This will save the image in "images" collection & update the "uploadedImage" value of document with id the same as the value of "id" variable.
await FirebaseFirestore.instance.collection(images).doc(id).update({'uploadedImage': _fileURL});
If you are updating an existing object then use the update method or else you can use the set method.
In your case you must follow bellow steps
First upload your image to Firebase Storage and get the download URL
Now you have the download URL and you can Upload your Enter object to Cloud FireStore with the url
Bellow method shows how could you store the image and get the download url list
Future<String> uploadImage(var imageFile ) async {
StorageReference ref = storage.ref().child("/photo.jpg");
StorageUploadTask uploadTask = ref.putFile(imageFile);
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
url = dowurl.toString();
return url;
}

Error appears only the first call, once the screen opens again, the error disappears,

As per the screenshot once I open the screen it gives me the error "The getter 'email' was called on null." but if I just click back button, then open the screen again, it works well without any error,
the purpose of the screen is the account owner see the notes that was sent to him from the admin account
This is the error appears only one time after opening the app
Here the same screen without any error
Here is the codes in dart where the tap to screen exists
import 'package:flutter/cupertino.dart' show CupertinoIcons;
import 'package:flutter/material.dart';
import 'package:notification_permissions/notification_permissions.dart';
import 'package:provider/provider.dart';
import 'package:rate_my_app/rate_my_app.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../app.dart';
import '../../common/config.dart';
import '../../common/constants.dart';
import '../../common/tools.dart';
import '../../generated/l10n.dart';
import '../../models/index.dart' show AppModel, User, UserModel, WishListModel;
import '../../routes/flux_navigate.dart';
import '../../screens/blogs/post_screen.dart';
import '../../services/index.dart';
import '../../widgets/common/webview.dart';
import '../custom/smartchat.dart';
import '../index.dart';
import '../users/user_point.dart';
import 'currencies.dart';
import 'language.dart';
import 'notification.dart';
import '../../common/config.dart' as config;
import 'package:cespohm/screens/bywaleed/booking_admin_screen.dart';
import 'package:cespohm/screens/bywaleed/docor_note_tap.dart';
import 'package:cespohm/screens/bywaleed/user_search_new_screen.dart';
import 'package:cespohm/screens/bywaleed/doctor_notes_user_screen.dart';
class SettingScreen extends StatefulWidget {
final List<dynamic> settings;
final String background;
final User user;
final VoidCallback onLogout;
final bool showChat;
SettingScreen({
this.user,
this.onLogout,
this.settings,
this.background,
this.showChat,
});
#override
_SettingScreenState createState() {
return _SettingScreenState();
}
}
class _SettingScreenState extends State<SettingScreen>
with
TickerProviderStateMixin,
WidgetsBindingObserver,
AutomaticKeepAliveClientMixin<SettingScreen> {
#override
bool get wantKeepAlive => true;
final bannerHigh = 150.0;
bool enabledNotification = true;
final RateMyApp _rateMyApp = RateMyApp(
// rate app on store
minDays: 7,
minLaunches: 10,
remindDays: 7,
remindLaunches: 10,
googlePlayIdentifier: kStoreIdentifier['android'],
appStoreIdentifier: kStoreIdentifier['ios']);
void showRateMyApp() {
_rateMyApp.showRateDialog(
context,
title: S.of(context).rateTheApp,
// The dialog title.
message: S.of(context).rateThisAppDescription,
// The dialog message.
rateButton: S.of(context).rate.toUpperCase(),
// The dialog "rate" button text.
noButton: S.of(context).noThanks.toUpperCase(),
// The dialog "no" button text.
laterButton: S.of(context).maybeLater.toUpperCase(),
// The dialog "later" button text.
listener: (button) {
// The button click listener (useful if you want to cancel the click event).
switch (button) {
case RateMyAppDialogButton.rate:
break;
case RateMyAppDialogButton.later:
break;
case RateMyAppDialogButton.no:
break;
}
return true; // Return false if you want to cancel the click event.
},
// Set to false if you want to show the native Apple app rating dialog on iOS.
dialogStyle: const DialogStyle(),
// Custom dialog styles.
// Called when the user dismissed the dialog (either by taping outside or by pressing the "back" button).
// actionsBuilder: (_) => [], // This one allows you to use your own buttons.
);
}
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, () async {
await checkNotificationPermission();
});
_rateMyApp.init().then((_) {
// state of rating the app
if (_rateMyApp.shouldOpenDialog) {
showRateMyApp();
}
});
}
// #override
// void dispose() {
// Utils.setStatusBarWhiteForeground(false);
// super.dispose();
// }
Future<void> checkNotificationPermission() async {
if (!isAndroid || isIos) {
return;
}
try {
await NotificationPermissions.getNotificationPermissionStatus()
.then((status) {
if (mounted) {
setState(() {
enabledNotification = status == PermissionStatus.granted;
});
}
});
} catch (err) {
printLog('[Settings Screen] : ${err.toString()}');
}
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
checkNotificationPermission();
}
}
/// Render the Admin Vendor Menu
Widget renderVendorAdmin() {
if (!(widget.user != null ? widget.user.isVendor ?? false : false)) {
return Container();
}
return Card(
color: Theme.of(context).backgroundColor,
margin: const EdgeInsets.only(bottom: 2.0),
elevation: 0,
child: ListTile(
onTap: () {
final String langCode =
Provider.of<AppModel>(context, listen: false).langCode;
if (unsupportedLanguages.contains(langCode)) {
final snackBar = SnackBar(
content: Text(
S.of(context).thisFeatureDoesNotSupportTheCurrentLanguage),
duration: const Duration(seconds: 1),
);
Scaffold.of(context).showSnackBar(snackBar);
return;
}
FluxNavigate.push(
MaterialPageRoute(
builder: (context) =>
Services().widget.getAdminVendorScreen(context, widget.user),
),
forceRootNavigator: true,
);
},
leading: Icon(
Icons.dashboard,
size: 24,
color: Theme.of(context).accentColor,
),
title: Text(
S.of(context).vendorAdmin,
style: const TextStyle(fontSize: 16),
),
trailing: Icon(
Icons.arrow_forward_ios,
size: 18,
color: Theme.of(context).accentColor,
),
),
);
}
/// Render the custom profile link via Webview
/// Example show some special profile on the woocommerce site: wallet, wishlist...
Widget renderWebViewProfile() {
if (widget.user == null) {
return Container();
}
var base64Str = Utils.encodeCookie(widget.user.cookie);
var profileURL = '${serverConfig["url"]}/my-account?cookie=$base64Str';
return Card(
color: Theme.of(context).backgroundColor,
margin: const EdgeInsets.only(bottom: 2.0),
elevation: 0,
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => WebView(
url: profileURL, title: S.of(context).updateUserInfor),
),
);
},
leading: Icon(
CupertinoIcons.profile_circled,
size: 24,
color: Theme.of(context).accentColor,
),
title: Text(
S.of(context).updateUserInfor,
style: const TextStyle(fontSize: 16),
),
trailing: Icon(
Icons.arrow_forward_ios,
color: Theme.of(context).accentColor,
size: 18,
),
),
);
}
Widget renderItem(value) {
IconData icon;
String title;
Widget trailing;
Function() onTap;
bool isMultiVendor = kFluxStoreMV.contains(serverConfig['type']);
switch (value) {
case 'bookingAdmin':
if (widget.user == null ) {
return Container();
}
else if(widget.user.email == config.adminEmail || widget.user.email == config.adminEmailTwo && widget.user != null )
{
icon = FontAwesomeIcons.keyboard;
title = S.of(context).checkout;
trailing =
const Icon(Icons.arrow_forward_ios, size: 18, color: kGrey600);
onTap = () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BookingAdminScreen()),
);
}
else {
return Container();
}
break;
case 'addDoctorNote':
if (widget.user == null ) {
return Container();
}
else if(widget.user.isVendor && widget.user != null )
{
icon = FontAwesomeIcons.edit;
title = S.of(context).continueToShipping;
trailing =
const Icon(Icons.arrow_forward_ios, size: 18, color: kGrey600);
onTap = () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => const UserSearchNewScreen()),
);
}
else {
return Container();
}
break;
/// here is the tap to the screen where there is the error
case 'yourDoctorNotes':
if (widget.user == null || widget.user.email == config.adminEmail || widget.user.email == config.adminEmailTwo ) {
return Container();
}
else if(!widget.user.isVendor)
{
icon = FontAwesomeIcons.notesMedical;
title = S.of(context).french;
trailing =
const Icon(Icons.arrow_forward_ios, size: 18, color: kGrey600);
onTap = () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => DoctorNoteUserScreen(senderUser: widget.user,)),
);
}
else {
return Container();
}
break;
case 'chat':
here is the dart code of the screen where is the error
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_provider.dart';
import 'package:cespohm/models/entities/user.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:provider/provider.dart';
import '../../generated/l10n.dart' as word;
import '../../models/index.dart' show AppModel, Store, User, UserModel ;
final _fireStore = FirebaseFirestore.instance;
firebase_auth.User loggedInUser;
class DoctorNoteUserScreen extends StatelessWidget {
final User senderUser;
DoctorNoteUserScreen({
Key key,
this.senderUser,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final userSearchProvider = Provider.of<UserSearchProvider>(context);
return Scaffold(
appBar: AppBar(
title: Text(
word.S.of(context).french,
style: TextStyle(
color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.w400),
),
leading: Center(
child: GestureDetector(
child: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onTap: () => Navigator.pop(context),
),
),
),
body: StreamBuilder<List<UserSearchModel>>(
stream: userSearchProvider.userstwo,
builder: (context, snapshot) {
if (!snapshot.hasData ) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).primaryColor),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(7.0),
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
SizedBox(
height: 40.0,
),
Text(word.S.of(context).french,
style: TextStyle(fontSize: 18.0)),
SizedBox(
height: 15.0,
),
Divider(
thickness: 1.0,
)
],
),
),
Container(
child: ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 15.0,
),
Container(
child: Text(snapshot.data[index].doctorNote!=null?snapshot.data[index].doctorNote: 'No Notes Yet',
style: TextStyle(fontSize: 20.0)),
),
],
),
),
),
],
),
);
});
}
}),
);
}
}
here is the dart code of the service
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_provider.dart';
import 'package:cespohm/models/user_model.dart';
class UserSearchService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
final userModel = UserModel();
//Get Entries
Stream<List<UserSearchModel>> getEntries(){
return _db
.collection('users')
.orderBy('firstName', descending: false)
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => UserSearchModel.fromJson(doc.data()))
.toList());
}
/// here is the firebase collection where the error exists
Stream<List<UserSearchModel>> getEntriesTwo(){
return _db
.collection('users').where('email', isEqualTo: userModel.user.email)
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => UserSearchModel.fromJson(doc.data()))
.toList());
}
}
here is the model
import 'package:cloud_firestore/cloud_firestore.dart';
class UserSearchModel {
final String date;
final String firstName;
final String lastName;
final String phone;
final String email;
final String searchKey;
final String doctorNote;
final String bYDoctor;
final String uID;
UserSearchModel(
{this.date,
this.firstName,
this.lastName,
this.phone,
this.email,
this.searchKey,
this.doctorNote,
this.bYDoctor,
this.uID});
// creating a Trip object from a firebase snapshot
UserSearchModel.fromSnapshot(DocumentSnapshot snapshot) :
date = snapshot['date'],
firstName = snapshot['firstName'].toDate(),
lastName = snapshot['lastName'].toDate(),
phone = snapshot['phone'],
email = snapshot['email'],
searchKey = snapshot['searchKey'],
doctorNote = snapshot['doctorNote'],
bYDoctor = snapshot['bYDoctor'],
uID = snapshot.id;
factory UserSearchModel.fromJson(Map<String, dynamic> json) {
return UserSearchModel(
date: json['createdAt'],
firstName: json['firstName'],
lastName: json['lastName'],
phone: json['phone'],
email: json['email'],
searchKey: json['searchKey'],
doctorNote: json['doctorNote'],
bYDoctor: json['bYDoctor'],
uID: json['uID']);
}
Map<String, dynamic> toMap() {
return {
'createdAt': date,
'firstName': firstName,
'lastName': lastName,
'phone': phone,
'email': email,
'searchKey': searchKey,
'doctorNote': doctorNote,
'bYDoctor': bYDoctor,
'uID': uID,
};
}
}
Here is the provider
import 'package:flutter/material.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/user_model.dart';
import 'package:cespohm/services/bywaleed/user_search_new_service.dart';
import 'package:uuid/uuid.dart';
class UserSearchProvider with ChangeNotifier {
final userSearchService = UserSearchService();
final userModel = UserModel();
DateTime _date;
String _firstName;
String _lastName;
String _phone;
String _email;
String _searchKey;
String _doctorNote;
String _bYDoctor;
String _uID;
var uuid = Uuid();
//Getters
DateTime get date => _date;
String get firstName => _firstName;
String get lastName => _lastName;
String get phone => _phone;
String get email => _email;
String get searchKey => _searchKey;
String get doctorNote => _doctorNote;
String get byDoctor => _bYDoctor;
String get uID => _uID;
Stream<List<UserSearchModel>> get users => userSearchService.getEntries();
Stream<List<UserSearchModel>> get userstwo => userSearchService.getEntriesTwo();
//Setters
set changeDate(DateTime date) {
_date = date;
notifyListeners();
}
set changeFirstName(String firstName) {
_firstName = firstName;
notifyListeners();
}
set changeLastName(String lastName) {
_lastName = lastName;
notifyListeners();
}
set changePhone(String phone) {
_phone = phone;
notifyListeners();
}
set changeEmail(String email) {
_email = email;
notifyListeners();
}
set changeSearchKey(String searchKey) {
_searchKey = searchKey;
notifyListeners();
}
set changeDoctorNote(String doctorNote) {
_doctorNote = doctorNote;
notifyListeners();
}
set changeBYDoctor(String bYDoctor) {
_bYDoctor = bYDoctor;
notifyListeners();
}
set changeuID(String uID) {
_uID = uID;
notifyListeners();
}
//Functions
loadAll(UserSearchModel userSearchModel) {
if (userSearchModel != null) {
_date = DateTime.parse(userSearchModel.date);
_firstName = userSearchModel.firstName;
_lastName = userSearchModel.lastName;
_phone = userSearchModel.phone;
_email = userSearchModel.email;
_searchKey = userSearchModel.searchKey;
_doctorNote = userSearchModel.doctorNote;
_bYDoctor = userModel.user.email;
_uID = userSearchModel.uID;
} else {
_date = DateTime.now();
_firstName = null;
_lastName = null;
_phone = null;
_email = null;
_searchKey = null;
_doctorNote = null;
_bYDoctor = null;
_uID = null;
}
}
saveEntry() {
if (_email == null) {
//Add
var newUserModel = UserSearchModel(
date: _date.toIso8601String(),
firstName: _firstName,
lastName: _lastName,
phone: _phone,
email: _email,
searchKey: _searchKey,
doctorNote: _doctorNote,
bYDoctor: _bYDoctor,
uID: _uID);
print(newUserModel.email);
userSearchService.setEntry(newUserModel);
} else {
//Edit
var updatedEntry = UserSearchModel(
date: _date.toIso8601String(),
firstName: _firstName,
lastName: _lastName,
phone: _phone,
email: _email,
searchKey: _searchKey,
doctorNote: _doctorNote,
bYDoctor: _bYDoctor,
uID: _uID);
userSearchService.setEntry(updatedEntry);
}
}
removeEntry(String entryId) {
userSearchService.removeEntry(entryId);
}
}
You need to make sure your User object is initialised. This error appears because user.email is accessed, but your User object is null. Make sure your code considers loading time for the user object if it comes from the API, and has appropriate checks for the case when user == null.

Can't get face detection to work properly using Flutter and Firebase_ml_vision

I've been struggling with this for about 24 hours now, and have come to the end of my ideas on how to address it.
I've written code which loads an image from Firebase, and detects a face in it - no problem at all. But when I then look to take a photo, using the standard imagePicker class in Flutter, despite me actually displaying the image on screen to check it's a valid file, the faceDetector can't find any faces in the image.
An edited down version of the code is below. Won't compile as there are things from my project missing, but hopefully you get the idea. The test platform is iOS (device, not emulator). Plugin is firebase_ml_vision 0.9.6+2, and the version of flutter is the latest from a few days ago.
Anyone have any ideas?
import 'package:flutter/material.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'dart:io';
import 'dart:async';
import 'package:camera/camera.dart';
class imageComparison extends StatefulWidget {
#override
_imageComparison createState() => _imageComparison();
}
class _imageComparison extends State<imageComparison> {
CameraController controller;
List<CameraDescription> cameras;
File chosenImage;
bool gotImage = false;
File grabbedImage;
FaceDetector faceDetector;
File tempImg;
#override
void initState() {
super.initState();
faceDetector = FirebaseVision.instance.faceDetector(FaceDetectorOptions(enableLandmarks: true, enableContours: true, enableClassification: true));
availableCameras().then((value) {
cameras = value;
controller = CameraController(cameras[1], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
});
}
#override
Widget build(BuildContext context) {
if (controller == null) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(),
);
}
if (!gotImage) {
File img;
downloadImage(imageURLs[0], 'verificationImage.jpg').then((value) {
img = tempImg = value;
extractFace(img).then((value2) {
print('got image');
gotImage = true;
setState(() {});
});
});
}
return Scaffold(
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: globals.showSpinner,
child: Container(
width: globals.SizeConfig.blockSizeHorizontal * 100,
height: globals.SizeConfig.blockSizeVertical * 100,
decoration: BoxDecoration(
gradient: gradient,
),
child: Stack(
children: <Widget>[
Positioned(
left: globals.SizeConfig.blockSizeHorizontal * 10,
top: globals.SizeConfig.blockSizeVertical * 5,
child: Column(
children: [
FlatButton(
child: Text(
'check',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: globals.SizeConfig.blockSizeHorizontal * 4),
),
color: Colors.red,
onPressed: () async {
bool res = await takeAndAnalyseImage();
//other stuff
},
),
],
),
),
],
),
),
),
);
}
Future<bool> takeAndAnalyseImage() async {
//String filepath = await takePicture();
grabbedImage = File((await ImagePicker().getImage(source: ImageSource.camera)).path);
//grabbedImage = File(filepath);
setState(() {
print('setting state');
});
while (grabbedImage == null) {}
if (mounted) {
extractFace(grabbedImage).then((value) {
//irrelevant stuff
});
}
return null;
}
Future<Map<String, dynamic>> extractFace(File img) async {
FirebaseVisionImage visionImage;
visionImage = FirebaseVisionImage.fromFile(img);
Map<String, dynamic> facevals = Map<String, dynamic>();
List<Face> faces;
try {
faces = await faceDetector.processImage(visionImage);
} catch (e) {
print('can\'t extract face from image. e = ' + e.toString());
}
for (Face face in faces) {
//do irrelevant stuff to question.
}
return facevals;
}
}
EDIT: The conversion of the image to 'FirebaseVisionImage' appears to work fine - it's the FaceDetector.processImage that fails...

Save Image from Image picker to firebase Storage in flutter

I am trying to upload image in firebase storage getting the image from image picker plugin by accessing camera. Image is not uploading. I also add I change the firebase rules so only authenticated users can upload the image. Git hub Repo. I used the image uploading logic defined at the auth_screen.dart Line No 48 to 59[I commented out for time being]. I also add as i add these line my other firebase fuctions which are running prefectly before. getting the errors.
auth_screen.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
// import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/services.dart';
import '../widgets/auth/auth_form.dart';
class AuthScreen extends StatefulWidget {
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final _auth = FirebaseAuth.instance;
var _isLoading = false;
void _submitAuthForm(
String email,
String password,
String userName,
File userImage,
bool isLogin,
BuildContext ctx,
) async {
dynamic authResult;
try {
setState(() {
_isLoading = true;
});
if (isLogin) {
authResult = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
} else {
print(email);
print(userName);
print(userImage.path);
authResult = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
// final FirebaseStorage storage = FirebaseStorage(
// app: FirebaseStorage.instance.app,
// storageBucket: 'gs://chatapp-1b780.appspot.com',
// );
// final StorageReference ref2 =
// storage.ref().child('userimage').child('${authResult.user.id}.jpg');
// final StorageUploadTask uploadTask = ref2.putFile(userImage);
// uploadTask.onComplete
// .then((value) => print(value))
// .catchError((error) => print(error));
// print(uploadTask.lastSnapshot.error.toString());
// ///...
// final ref = FirebaseStorage.instance
// .ref()
// .child('user_image')
// .child(authResult.user.id + '.jpg');
// await ref.putFile(userImage).onComplete;
///
await FirebaseFirestore.instance
.collection('users')
.doc(authResult.user.uid)
.set({
'username': userName,
'email': email,
});
}
} on PlatformException catch (error) {
var message = 'An error occured,Please check your credentials';
if (error.message != null) {
setState(() {
_isLoading = false;
});
message = error.message;
}
print(message);
} catch (error) {
setState(() {
_isLoading = false;
});
Scaffold.of(ctx).showSnackBar(
SnackBar(
content: Text(error.toString()),
backgroundColor: Theme.of(ctx).errorColor,
),
);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).primaryColor,
body: AuthForm(_submitAuthForm, _isLoading),
);
}
}
image being picked using image picker from auth/auth_form.dart to user_image_picker.dart where i added the argument so the image is passed down.
auth/authform.dart
import 'package:flutter/material.dart';
import 'dart:io';
import '../pickers/user_image_picker.dart';
class AuthForm extends StatefulWidget {
final bool isLoading;
final void Function(String email, String password, String userName,
File userImage, bool isLogin, BuildContext ctx) submitFn;
AuthForm(this.submitFn, this.isLoading);
#override
_AuthFormState createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
final _formKey = GlobalKey<FormState>();
var _isLogin = true;
String _userEmail = '';
String _userName = '';
String _userPassword = '';
File _userImageFile;
void _pickedImage(File image) {
_userImageFile = image;
}
void _trysubmit() {
final isValid = _formKey.currentState.validate();
FocusScope.of(context).unfocus();
if (_userImageFile == null && !_isLogin) {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text('Please Pick an Image'),
backgroundColor: Theme.of(context).errorColor,
),
);
return;
}
if (isValid) {
_formKey.currentState.save();
print(_userEmail);
print(_userPassword);
widget.submitFn(_userEmail.trim(), _userPassword.trim(), _userName.trim(),
_userImageFile, _isLogin, context);
print(_userEmail);
print(_userPassword);
}
}
#override
Widget build(BuildContext context) {
return Center(
child: Card(
margin: EdgeInsets.all(20),
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (!_isLogin)
UserImagePicker(
imagePickFn: _pickedImage,
),
TextFormField(
key: ValueKey('emailAdress'),
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email address',
),
validator: (value) {
if (value.isEmpty || !value.contains('#')) {
return 'Please return a valid email address';
}
return null;
},
onSaved: (newValue) {
_userEmail = newValue;
},
),
if (!_isLogin)
TextFormField(
key: ValueKey('userName'),
decoration: InputDecoration(labelText: 'Username'),
validator: (value) {
if (value.isEmpty || value.length < 4) {
return 'Please Enter at least 4 characters';
}
return null;
},
onSaved: (newValue) {
_userName = newValue;
},
),
TextFormField(
key: ValueKey('password'),
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value.isEmpty || value.length < 7) {
return 'Please Enter at least 7 characters';
}
return null;
},
onSaved: (newValue) {
_userPassword = newValue;
},
),
SizedBox(
height: 12,
),
if (widget.isLoading) CircularProgressIndicator(),
if (!widget.isLoading)
RaisedButton(
onPressed: _trysubmit,
child: Text((_isLogin) ? 'Login' : 'SignUp'),
),
if (!widget.isLoading)
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(_isLogin
? 'Create new account'
: 'I already have an account'),
onPressed: () {
setState(() {
_isLogin = !_isLogin;
});
},
),
],
),
),
),
),
),
),
);
}
}
user_image_picker.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class UserImagePicker extends StatefulWidget {
UserImagePicker({this.imagePickFn});
final void Function(File pickedImage) imagePickFn;
#override
_UserImagePickerState createState() => _UserImagePickerState();
}
class _UserImagePickerState extends State<UserImagePicker> {
File _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await ImagePicker().getImage(source: ImageSource.camera);
setState(() {
_image = File(pickedFile.path);
});
widget.imagePickFn(_image);
}
#override
Widget build(BuildContext context) {
return Column(
children: [
CircleAvatar(
radius: 40,
backgroundColor: Colors.grey,
backgroundImage: _image != null ? FileImage(_image) : null,
),
FlatButton.icon(
onPressed: getImage,
icon: Icon(Icons.image),
label: Text('Add Image'),
textColor: Theme.of(context).primaryColor,
),
],
);
}
}
Since you asked me to show you how to upload images to Firebase Storage, I will show you the whole procedure including using the Image Picker plugin. This is how you should use Image Picker:
class PickMyImage{
static Future<File> getImage() async {
final image = await ImagePicker().getImage(
source: ImageSource.gallery,
maxHeight: 1500,
maxWidth: 1500,
);
if (image != null) {
return File(image.path);
}
return null;
}
}
This is how you can get and upload that image to firebase storage:
final File _myImage=await PickMyImage.getImage();
if(_myImage!=null){
final StorageReference firebaseStorageRef = FirebaseStorage.instance
.ref()
.child("user/${_auth.currentUser().uid}/i"); //i is the name of the image
StorageUploadTask uploadTask =
firebaseStorageRef.putFile(_myImage);
StorageTaskSnapshot storageSnapshot = await uploadTask.onComplete;
var downloadUrl = await storageSnapshot.ref.getDownloadURL();
if (uploadTask.isComplete) {
final String url = downloadUrl.toString();
print(url);
//You might want to set this as the _auth.currentUser().photourl
} else {
//error uploading
}
}
The issue i got because i am returning the ImagePicker() function of the file then gettting the image from camera then passing the file to the Fire Storage bucket.
In user_image_picker.dart
I written this
final pickedFile = await ImagePicker().getImage(source: ImageSource.camera);
Instead of i have to write this
final pickedFile = await picker.getImage(source: ImageSource.camera);

Resources