Ill try and provide as much code as possible. (mainly regarding the image ill be using "other data" instead of posting non needed code besides the image)
So in my app I have a File image; provider and im having issues with getting to display it on my app. Im unable to pass the File image path into firebase and its causing my app to crash when I try Fetching the data from firebase. Ill try providing as much code as possible.
Here is my provider:
import 'dart:io';
class AddCar {
// other data
File image;
AddCar({
// other data
this.image,
});
}
Here is my provider code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import '../add_ons/add_car.dart';
List<AddCar> _cars = [];
class Cars with ChangeNotifier {
List<AddCar> get cars {
return [..._cars];
}
Future<void> fetchAndSetCars() async {
const url = 'https://mycustomlink.firebaseio.com/cars.json';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
var loadedCars = extractedData
.map<String, AddCar>((carId, carData) => MapEntry(
carId,
AddCar(
// other data
image: File(carData['image']),
)))
.values
.toList();
_cars = loadedCars;
print(extractedData);
print(loadedCars);
notifyListeners();
} catch (error) {
throw (error);
}
}
AddCar findById(String id) {
return _cars.firstWhere((carProd) => carProd.id == id);
}
void addCar(AddCar car) {
const url = 'https://mycustomlink.firebaseio.com/cars.json';
http.post(
url,
body: json.encode({
// other data
'image': car.image.toString(),
}),
);
final newCar = AddCar(
// other data
image: car.image,
);
_cars.insert(0, newCar);
notifyListeners();
}
}
here is my form where the user enters data for it to be displayed:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/app_localization.dart';
import 'package:google_fonts_arabic/fonts.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as syspaths;
import '../add_ons/add_car.dart';
import '../providers/car_provider.dart';
import '../drawer/drawer.dart';
import '../screens/cars_screen.dart';
import '../app_localization.dart';
class CreateCar extends StatefulWidget {
static const routeName = '/create-car';
#override
_CreateCarState createState() => _CreateCarState();
}
class _CreateCarState extends State<CreateCar> {
final _name = TextEditingController();
final _price = TextEditingController();
final _address = TextEditingController();
String img;
static Future<String> fileToB64(File f) async {
List<int> imageBytes = f.readAsBytesSync();
return base64Encode(
imageBytes,
);
}
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
);
fileToB64(data.image).then((d) {
setState(() {
img = d; //base64Decode(d);
});
});
}
final _form = GlobalKey<FormState>();
int currStep = 0;
static AddCar data = new AddCar(
id: null,
date: DateTime.now(),
sponsNum: '',
);
void _saveForm() {
final isValid = _form.currentState.validate();
if (!isValid) {
return;
}
_form.currentState.save();
Provider.of<Cars>(context, listen: false).addCar(data);
Navigator.of(context).pushNamed(CarsScreen.routeName);
print('this works');
}
#override
Widget build(BuildContext context) {
List<Step> steps = [
Step(
title: Text(
AppLocalizations.of(context).createTabTitle,
),
isActive: true,
state: StepState.indexed,
content: Column(
children: <Widget>[
// other data
],
),
),
Step(
title: Text(
AppLocalizations.of(context).createCarDetails,
),
isActive: true,
state: StepState.indexed,
content: Column(
children: <Widget>[
// other data
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 25.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.circular(50.0),
),
child: FlatButton(
child: Text(AppLocalizations.of(context).createAddImages),
onPressed: _takePicture,
),
),
)
],
)
],
),
),
];
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
AppLocalizations.of(context).createCarPageTitle,
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: ArabicFonts.Tajawal,
package: 'google_fonts_arabic',
),
),
actions: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.save),
onPressed: _saveForm,
),
IconButton(
icon: Icon(Icons.arrow_forward),
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
],
),
drawer: MyDrawer(),
body: Row(
children: <Widget>[
Form(
key: _form,
child: Expanded(
child: Stepper(
steps: steps,
type: StepperType.vertical,
currentStep: this.currStep,
onStepContinue: () {
setState(() {
if (currStep < steps.length - 1) {
currStep = currStep + 1;
} else {
// currStep = 0;
}
});
},
onStepCancel: () {
setState(() {
if (this.currStep > 0) {
this.currStep = this.currStep - 1;
} else {
this.currStep = 0;
}
});
},
onStepTapped: (step) {
setState(() {
currStep = step;
});
},
),
),
),
],
),
);
}
}
which is later passed into my "CarItem" that will display my code:
import 'package:flutter/material.dart';
import 'package:google_fonts_arabic/fonts.dart';
import '../icons/MyIcons.dart';
import 'dart:io';
import '../details/car_details.dart';
import '../app_localization.dart';
class CarItem extends StatelessWidget {
final File image;
CarItem(
this.image,
);
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).primaryColor, width: 2.0),
),
),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 245, 245, 245),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(17.0, 4.0, 17.0, 4.0),
child: Row(
textDirection: TextDirection.rtl,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
// other data
],
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.35,
height: MediaQuery.of(context).size.width * 0.35,
child: GestureDetector(
child: Image.file(
image,
fit: BoxFit.fill,
),
onTap: () {
Navigator.of(context).pushNamed(
MyCarDetails.routeName,
arguments: id,
);
},
),
),
Container(
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.all(0),
padding: const EdgeInsets.fromLTRB(22.0, 5.0, 22.0, 0),
child: Column(
children: <Widget>[
// other data
],
),
),
],
),
),
],
),
],
),
);
}
}
this code gets called by a list that will call the code and display it in my app:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts_arabic/fonts.dart';
import '../providers/car_provider.dart';
import '../widget/car_item.dart';
class CarsList extends StatefulWidget {
#override
_CarsListState createState() => _CarsListState();
}
class _CarsListState extends State<CarsList> {
#override
Widget build(BuildContext context) {
final carsData = Provider.of<Cars>(context);
final car = carsData.cars;
return car.isEmpty
? Center(
child: Text(
'no data yet available',
style: TextStyle(
fontFamily: ArabicFonts.Tajawal,
fontWeight: FontWeight.bold,
package: 'google_fonts_arabic',
),
))
: ListView.builder(
padding: const EdgeInsets.only(bottom: 47.0),
itemCount: car.length,
itemBuilder: (ctx, i) => CarItem(
// other data
car[i].image,
),
);
}
}
this is the error i keep getting when It tries to display fetched data:
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building CarItem(dirty, dependencies: [_LocalizationsScope-[GlobalKey#31697], MediaQuery, _InheritedTheme]):
The method '+' was called on null.
Receiver: null
Tried calling: +("25")
User-created ancestor of the error-causing widget was
ListView
lib\home_parts\cars_area.dart:49
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 CarItem.build
package:flutter_app/widget/car_item.dart:151
#2 StatelessElement.build
package:flutter/…/widgets/framework.dart:4009
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:3941
#4 Element.rebuild
package:flutter/…/widgets/framework.dart:3738
...
════════════════════════════════════════════════════════════════════════════════
How can I fix this? is the issue in how im passing the data to firebase and displaying it on my app?
Related
I am integrating file uploading system in my flutter project using firebase.
While making progress indicator I am getting undefined name 'uploadTask' error.
In this project we can upload file,image and many more to firebase and simultaneously view at the same time.
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future selectFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
}
Future uploadFile() async {
final path = 'files/${pickedFile!.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() => null);
final urlDownload = await snapshot.ref.getDownloadURL();
print('Download link: $urlDownload');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if (pickedFile != null)
Expanded(
child: Container(
color: Colors.blue[100],
child: Center(
child: Image.file(
File(pickedFile!.path!),
width: double.infinity,
fit: BoxFit.cover,
),
),
),
),
SizedBox(
height: 32,
),
ElevatedButton(
onPressed: selectFile,
child: const Text(
'Select File',
),
),
ElevatedButton(
onPressed: uploadFile,
child: const Text(
'Upload File',
),
),
buildProgress(),
],
),
),
),
);
}
}
Widget buildProgress() => StreamBuilder<TaskSnapshot>(
stream: uploadTask?.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey,
color: Colors.green,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()}%',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
);
I am creating a system that only certain user can see the list of the projects. The list of the projects will be shown in user application when the projects have been assigned to them thru administration by using user's email. I am using flutter and google firebase
I tried to use If else statement but I seem can't do it.
I have 2 model classes
User_model class
import 'package:firebase_auth/firebase_auth.dart';
class Users{
final String uid;
Users({this.uid});
}
class UserModel{
String uid;
String email;
String name;
String employeeID;
String phonenumber;
String position;
UserModel({this.uid, this.email, this.name, this.employeeID, this.phonenumber, this.position});
//receiving data from server
factory UserModel.fromMap(map){
return UserModel(
uid: map['uid'],
email: map['email'],
name: map['name'],
employeeID: map['employeeID'],
phonenumber: map['phonenumber'],
position: map['position'],
);
}
//sending data to our server
Map<String, dynamic> toMap(){
return{
'uid': uid,
'email': email,
'name' : name,
'employeeID' : employeeID,
'phonenumber' : phonenumber,
'position' : position,
};
}
}
class UserProject{
final String projectid;
final String address;
final String titleproject;
final List<String> assignedmember ;
UserProject({this.projectid, this.address, this.titleproject, this.assignedmember});
}
Project_model class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class Project{
final String address;
final String titleproject;
final List<dynamic> assignedmember;
Project({this.address, this.titleproject, this.assignedmember});
}
HomeScreen.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/data/user_model.dart';
import 'package:smartconstructionreport/screens/project_screen.dart';
import 'package:smartconstructionreport/theme.dart';
import 'package:smartconstructionreport/widget/ProjectCard.dart';
import 'package:smartconstructionreport/widget/menulist.dart';
import 'package:smartconstructionreport/service/database.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:smartconstructionreport/widget/projectlist.dart';
import 'FloorPlan.dart';
class HomeScreen extends StatefulWidget {
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
User user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
#override
void initState(){
super.initState();
FirebaseFirestore.instance
.collection("user")
.doc(user.uid)
.get()
.then((value){
this.loggedInUser = UserModel.fromMap(value.data());
setState(() {});
});
}
Widget build(BuildContext context) {
return StreamProvider<List<Project>>.value(
value: DatabaseService().projects,
child: Scaffold(
drawer: menulist(),
appBar: AppBar(
backgroundColor: kPrimaryColor,
centerTitle: true,
title: Image.asset('images/scdr logo.png',
fit: BoxFit.cover,),
),
body: SingleChildScrollView(
child: Padding(
padding: kDefaultPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 30,
),
Text(
"Hello ${loggedInUser.name},",
style: TextStyle(color: Colors.black,
fontSize: 25,
fontWeight: FontWeight.w700),
),
SizedBox(
height: 5,
),
Text(
'Have a great day ahead!',
style: TextStyle(color: Colors.black,
fontSize: 12,
),
),
SizedBox(
height: 5,
),
Text(
'Lets start working!',
style: TextStyle(color: Colors.black,
fontSize: 12,
),
),
SizedBox(
height: 30,
),
Text(
'Project Lists',
style: TextStyle(color: Colors.black,
fontSize: 25,
fontWeight: FontWeight.w700),
),
SizedBox(
height: 18,
),
ProjectList(),
],
),
),
),
),
);
}
}
ProjectList.dart
I tried to add If else statement to check if the project contains email assigned to the project. But it return null
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:provider/provider.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/screens/project_screen.dart';
import 'ProjectCard.dart';
class ProjectList extends StatefulWidget {
#override
_ProjectListState createState() => _ProjectListState();
}
class _ProjectListState extends State<ProjectList> {
User user = FirebaseAuth.instance.currentUser;
Project projectmember = Project();
#override
Widget build(BuildContext context) {
final projects = Provider.of<List<Project>>(context) ?? [];
return ListView.builder(
shrinkWrap: true,
itemCount: projects.length,
itemBuilder: (context, index) {
if (projectmember.assignedmember.contains(user.email)) {
return ProjectCard(project: projects[index],
press: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProjectScreen(),
));
},
);
};
}
);
}
}
ProjectCard.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smartconstructionreport/data/project_model.dart';
import 'package:smartconstructionreport/theme.dart';
class ProjectCard extends StatelessWidget {
final Function press;
final Project project;
ProjectCard({this.project, this.press});
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return GestureDetector(
onTap: press,
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)
),
elevation: 10,
margin: EdgeInsets.fromLTRB(5.0, 15.0, 5.0, 10.0),
child: Column(
children: [
Stack(
alignment: Alignment.center,
children: [
Padding(
padding: const EdgeInsets.all(2.0),
child: Text(
project.titleproject,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
)
],
),
Divider(color: Colors.black),
Padding(
padding: EdgeInsets.fromLTRB(10.0, 5.0, 5.0, 0.0),
child: Text(
project.address,
style: TextStyle(fontSize: 14),),
),
Row(
children: [
Column(
children: [
TextButton.icon(
onPressed: (){},
icon: Icon(Icons.person,
color: kPrimaryColor,) ,
label: Text('Project Manager')),
],
),
SizedBox(width:50),
Column(
children: [
TextButton.icon(
onPressed: (){},
icon: Icon(Icons.location_pin,
color: kPrimaryColor,) ,
label: Text('MAP')),
],
)
],
),
],
),
),
);
}
}
Error
======== Exception caught by widgets library =======================================================
The method 'contains' was called on null.
Receiver: null
Tried calling: contains("rashid#fyp.com")
====================================================================================================
I've created a flutter project that show a staggeredgridview of images from firestore database. Once i click on one of the images it shows that image. What i want is a download button thats saves the image to my device. Ath the moment I've just used pop.
I've read some about the path provider package but i can't figure out how to implement this in the code. Perhaps there is a better solution?
StaggeredGridView Page
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:proj/screens/home/instafull.dart';
import 'dart:async';
import 'package:proj/services/auth.dart';
import 'package:proj/shared/constants.dart';
class Instapage extends StatefulWidget {
#override
_InstapageState createState() => _InstapageState();
}
class _InstapageState extends State<Instapage> {
final AuthService _auth = AuthService();
StreamSubscription<QuerySnapshot> subscription;
List<DocumentSnapshot> wallpaperlist;
final CollectionReference collectionReference = FirebaseFirestore.instance.collection('mediapost');
#override
void initState() {
// TODO: implement initState
super.initState();
subscription = collectionReference.snapshots().listen((datasnapshot) {
setState(() {
wallpaperlist = datasnapshot.docs;
});
});
}
#override
void dispose() {
subscription?.cancel();
// TODO: implement dispose
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: bas,
body: wallpaperlist != null?
StaggeredGridView.countBuilder(
padding: const EdgeInsets.fromLTRB(10, 8, 10, 0),
crossAxisCount: 4,
itemCount: wallpaperlist.length,
itemBuilder: (context, index){
String imgPath = wallpaperlist[index].get('img');
return new Material(
elevation: 8,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
child: InkWell(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InstaFull(imgPath: imgPath))),
child: Hero(
tag: imgPath,
child: FadeInImage(
image: NetworkImage(imgPath),
fit: BoxFit.cover,
placeholder: AssetImage('assets/wally2.jpg'),
),
),
),
);
},
staggeredTileBuilder: (index) => StaggeredTile.count(2, index.isEven?2:3),
mainAxisSpacing: 8,
crossAxisSpacing: 8,
): Center(
child: CircularProgressIndicator(),
),
);
}
}
Picture Page
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class InstaFull extends StatelessWidget {
String imgPath;
InstaFull({this.imgPath});
final LinearGradient backgroundGradient = LinearGradient(
colors: [Color(0x10000000), Color(0x30000000)],
begin: Alignment.topLeft,end: Alignment.bottomRight);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand(
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Hero(
tag: imgPath,
child: Image.network(imgPath),
),
),
Align(
alignment: Alignment.topCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: IconButton(
icon: Icon(Icons.close,
color: Colors.black,
),
onPressed: () => Navigator.of(context).pop(),
),
),
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Download')),
],),
)
],
),
),
);
}
}
You can use gallery_saver
Install it and enable this permissions:
iOS
Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
Android
Android
android.permission.WRITE_EXTERNAL_STORAGE - Permission for usage of external storage
Official example of gallery_saver:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String firstButtonText = 'Take photo';
String secondButtonText = 'Record video';
double textSize = 20;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
Flexible(
flex: 1,
child: Container(
child: SizedBox.expand(
child: RaisedButton(
color: Colors.blue,
onPressed: _takePhoto,
child: Text(firstButtonText,
style:
TextStyle(fontSize: textSize, color: Colors.white)),
),
),
),
),
Flexible(
child: Container(
child: SizedBox.expand(
child: RaisedButton(
color: Colors.white,
onPressed: _recordVideo,
child: Text(secondButtonText,
style: TextStyle(
fontSize: textSize, color: Colors.blueGrey)),
),
)),
flex: 1,
)
],
),
),
));
}
void _takePhoto() async {
ImagePicker.pickImage(source: ImageSource.camera)
.then((File recordedImage) {
if (recordedImage != null && recordedImage.path != null) {
setState(() {
firstButtonText = 'saving in progress...';
});
GallerySaver.saveImage(recordedImage.path).then((String path) {
setState(() {
firstButtonText = 'image saved!';
});
});
}
});
}
void _recordVideo() async {
ImagePicker.pickVideo(source: ImageSource.camera)
.then((File recordedVideo) {
if (recordedVideo != null && recordedVideo.path != null) {
setState(() {
secondButtonText = 'saving in progress...';
});
GallerySaver.saveVideo(recordedVideo.path).then((String path) {
setState(() {
secondButtonText = 'video saved!';
});
});
}
});
}
void _saveNetworkVideo() async {
String path =
'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4';
GallerySaver.saveVideo(path).then((bool success) {
setState(() {
print('Video is saved');
});
});
}
void _saveNetworkImage() async {
String path =
'https://image.shutterstock.com/image-photo/montreal-canada-july-11-2019-600w-1450023539.jpg';
GallerySaver.saveImage(path).then((bool success) {
setState(() {
print('Image is saved');
});
});
}
}
Tried signing up user with Firebase but got the above error instead, and the code is formatted in such a way that it should redirect the user to homepage after a successful signup.
My main.dart
import 'package:bedc_app/home_page.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:bedc_app/auth/login_page.dart';
void main() async{
//solution study
WidgetsFlutterBinding.ensureInitialized();
FirebaseAuth.instance.currentUser()
.then((FirebaseUser user) {
if(user != null){
Firestore.instance.collection('users').document(user.uid).get().then((DocumentSnapshot doc){
runApp(MyApp(true, doc));
});
return;
}
runApp(MyApp(false, null));
});
}
// void main() =>runApp(MyApp());
class MyApp extends StatelessWidget {
bool isLoggedIn;
DocumentSnapshot doc;
MyApp(this.isLoggedIn, this.doc);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Multifunctional bedc project App',
debugShowCheckedModeBanner: false,
home: isLoggedIn ? HomePage(userDoc: doc) : loginPage(),
);
}
}
My Signup_page.dart
import 'package:bedc_app/auth/login_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:bedc_app/utils/constants.dart';
import '../home_page.dart';
class SignUpPage extends StatefulWidget {
#override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
String email, password;
bool isLoggedIn = false;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ListView(
children: [
SizedBox(
height: 50,
),
Align(
alignment: Alignment.topCenter,
child: (
Image.asset(
'assets/bedclogo.jpg'
)),
),
SizedBox(
height: 100,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26.0),
child: TextField(
decoration: InputDecoration(
hintText: 'email',
border: OutlineInputBorder(),
labelText: 'Email',
suffixIcon: Icon(Icons.email, color: Colors.green)
),
keyboardType: TextInputType.emailAddress,
onChanged: (String val){
email = val;
},
),
),
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26.0),
child: TextField(
decoration: InputDecoration(
hintText: 'Password',
border: OutlineInputBorder(),
labelText: 'Password',
suffixIcon: Icon(Icons.lock, color: Colors.green)
),
obscureText: true,
obscuringCharacter: '!',
keyboardType: TextInputType.emailAddress,
onChanged: (String val){
password = val;
},
),),
SizedBox(
height: 5,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 26),
child: MaterialButton(
color: Color(0xFF88C540),
child: isLoading ? Container(
height: 24,
width: 24,
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
strokeWidth: 2,
)
):Text(
'SignUp'.toUpperCase(),
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: (){
checkUserInput();
},
),
),
SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: RichText(
text: TextSpan(
text: 'Already have an Account ?',
style: TextStyle(color: Colors.black),
children: [
TextSpan(
text: 'Login here',
style: TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()..onTap = (){
Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_) => loginPage()));
},
)
]
)),
)
],
));
}
//SIGNUP FUNCTION USING FIREBASE
bool isLoading = false;
signUpUserWithFirebase(){
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password
).then((AuthResult result){
//Authresult cant be stored to string.....
storeUserDataToFirestore(result.user.uid);
if(result.user.uid != null){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomePage()));
}
}).catchError((e){
print(e);
isLoading = false;
setState(() { });
});
}
//storeUserDataToFirestore
storeUserDataToFirestore(String userId){
Map<String, dynamic> userData = Map<String, dynamic>();
userData = {
Constants.USERNAME: '#username',
Constants.USER_ID: userId,
Constants.EMAIL : email,
Constants.ACCOUNT_NUM : '00000000',
Constants.IS_ADMIN: false,
Constants.PROFILE_IMAGE: '',
Constants.PROFILE_IMAGE_THUMB: '',
};
CollectionReference usersRef = Firestore.instance.collection(Constants.USERS_COLLECTION);
usersRef.document(userId).setData(userData).then((_){
isLoading = false;
setState(() { });
}).catchError((e){
print(e);
});
}
//FUNCTION TO CHECK USER ENTRY
checkUserInput(){
isLoading = true;
setState(() { });
if(email == null || email.isEmpty){
print('Enter email');
isLoading = false;
setState(() { });
return;
}
if(password == null || email.isEmpty){
print('Enter password');
isLoading = false;
setState(() { });
}
//SIGNUP THE USER
signUpUserWithFirebase();
}
getUserData(String UserId){
Firestore.instance.collection(Constants.USERS_COLLECTION)
.document(UserId)
.get().then((DocumentSnapshot userDoc){
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_) => HomePage(userDoc: userDoc)));
}).catchError((e){
print(e);
});
}
}
My Home_page.dart
import 'dart:ui';
import 'package:bedc_app/auth/login_page.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:bedc_app/auth/signup_page.dart';
import 'model/user.dart';
User currentUser;
class HomePage extends StatefulWidget {
DocumentSnapshot userDoc;
HomePage({this.userDoc,});
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//user cant access this page unless logged in
bool userIsLoggedIn = true;
#override
void initState() {
// TODO: implement initState
super.initState();
currentUser = User.fromSnapshot(widget.userDoc);
}
//HERE IS BUILDING PROFILE IMAGE
Widget buildProfileImage(){
if(currentUser.profileImage == ''){
return CircleAvatar(
backgroundColor: Colors.white70,
radius: 20,
child: Icon(Icons.person, size: 30),
);
}else{
return CircleAvatar(
backgroundImage: NetworkImage(currentUser.profileImage),
);
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.brown,
title: Text('Homepage'),
),
body: ListView(
children: [
SizedBox(height: 20),
Align(
alignment: Alignment.topRight,
child: (
Image.asset(
'assets/bedclogo.jpg',
scale: 2,
)),
),
ListTile(
title: Text(currentUser.username, style: TextStyle(color: Colors.brown, fontWeight: FontWeight.bold),),
leading: buildProfileImage(),
),
SizedBox(height: 30),
//CAPTURE METER READING UI
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: GestureDetector(
onTap: (){
//print(currentUser.isAdmin);
},
child: Row(
children: [
//CAPTURE METR READING
Container(
width: 100,
height: 100,
color: Colors.green,
child: Align(
alignment: Alignment.center,
child: (
Image.asset(
'assets/meterIcon.png',
scale: 3,
)),
),
),
Container(
width: 100,
height: 100,
child: Align(
alignment: Alignment.center,
child: Text('Capture Meter Reading'.toUpperCase()),
),
),
],
),
),
),
SizedBox(height: 30),
//UPDATE PROFILE UI DESIGN
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: GestureDetector(
onTap:(){
//print(currentUser.isAdmin);
},
child: Row(
children: [
Container(
width: 100,
height: 100,
color: Colors.green,
child: Align(
alignment: Alignment.center,
child: (
Image.asset(
'assets/profileAvatar.png',
scale: 3,
)),
),
),
Container(
width: 100,
height: 100,
child: Align(
alignment: Alignment.center,
child: Text('Update Profile'.toUpperCase()),
),
),
],
),
),
),
// TextButton (
// onPressed: (){
// //just logout, implement pop dialog later
// // FirebaseAuth.instance.signOut();
// // Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: (_)=> loginPage()));
// // currentUser = null;
// // setState(() {
// // });
// // still showing error... try to fix asap
// FirebaseAuth.instance.signOut().then((_){
// userIsLoggedIn = false;
// Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=> loginPage()));
// //currentUser = null;
// setState(() {
//
// });
// });
// },
// child: Text('SignOut'))
],
)
);
}
}
User.dart for user Model
import 'package:bedc_app/utils/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class User{
String username;
String email;
String userId;
String accountNum;
bool isAdmin;
String profileImage;
String profileImageThumb;
User({
this.username,
this.email,
this.userId,
this.accountNum,
this.isAdmin,
this.profileImage,
this.profileImageThumb
});
factory User.fromSnapshot(DocumentSnapshot doc){
return User(
username: doc.data[Constants.USERNAME],
email: doc.data[Constants.EMAIL],
userId: doc.data[Constants.USER_ID],
accountNum: doc.data[Constants.ACCOUNT_NUM],
isAdmin: doc.data[Constants.IS_ADMIN],
profileImage: doc.data[Constants.PROFILE_IMAGE],
profileImageThumb: doc.data[Constants.PROFILE_IMAGE_THUMB]
);
}
}
Having signed the user up, im getting error The getter 'data' was called on null. Receiver: null Tried calling: data.
i dont know which part of the code is causing this exception
This error generally show when you try to get some attribute on null object.
In your case, call one of doc.data[..] in file User.dart generate the error that means doc == null is true.
Verify that widget.userDoc is not null at this line currentUser = User.fromSnapshot(widget.userDoc); on initState method of Home_page.dart file
So error provide in one of HomePage call who require a non null userDoc (todo: make sure your data is not null using assert and add #required before required variable on your class exp: HomePage({#required this.userDoc,}): assert(userDoc != null, "BOooh my userDoc may be not null"); that help very much when you debug your app)
finaly your problem provide in signUpUserWithFirebase() method of your Signup_page.dart file... here Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomePage()));
Try to replace by this getUserData(result.user.uid) so your methode should become
signUpUserWithFirebase(){
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password
).then((AuthResult result){
//Authresult cant be stored to string.....
storeUserDataToFirestore(result.user.uid);
if(result.user.uid != null){
getUserData(result.user.uid); // replaced line
}
}).catchError((e){
print(e);
isLoading = false;
setState(() { });
});
}
I received a project to do facial recognition, which was recorded by the user in a video, to avoid fraud. The user records a video of +/- 5 seconds, and the code takes his face, and sends it to a bank. It turns out that my code gives a very strange error. The code takes the video from the library, but saves it in .jpg, and when you press "Scan" this error appears:
E/flutter (10653): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: 'package:firebase_ml_vision/src/firebase_vision.dart': Failed assertion: line 111 pos 12: 'imageFile != null': is not true.
I looked everywhere and found nothing to help me.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:flutter_app_face/face_detector_controller.dart';
class MyFaceDetectorView extends StatefulWidget {
#override
_MyFaceDetectorViewState createState() => _MyFaceDetectorViewState();
}
class _MyFaceDetectorViewState extends State<MyFaceDetectorView> {
final _picker = ImagePicker();
File _videoFile;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Face Detector",
style: TextStyle(fontSize: 30),
),
centerTitle: true,
),
body: myFaceView(),
);
}
myFaceView() {
return SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
child: Container(
child: Column(
children: [
Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Select a file",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(10),
child: CircleAvatar(
child: IconButton(
icon: Icon(Icons.video_library),
onPressed: () async => await pickVideo(),
),
),
),
],
),
Padding(
padding: EdgeInsets.only(bottom: 18),
child: RaisedButton(
child: Text("Scan", style: TextStyle(fontSize: 16)),
onPressed: scanner,
color: Colors.orange,
),
),
],
)),
),
],
),
),
);
}
scanner() {
List<Face> faces;
if (faces != null) {
return _alert();
} else {
FaceDetectorController faceDetec = FaceDetectorController();
faceDetec.pickVideo(_videoFile);
print("scanned");
}
}
Future<void> _alert() {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('No faces found'),
content: const Text(
'We didn't find anything in your file, please try again.'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
pickVideo() async {
final PickedFile videoFile = await _picker.getVideo(
source: ImageSource.gallery,
maxDuration: Duration(seconds: 5),
);
setState(() {
this._videoFile = File(videoFile.path);
});
print("Finish");
}
}
Controller:
import 'dart:io';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
class FaceDetectorController {
pickVideo(File video) async {
final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(video);
print('VisionImage: $video');
final FaceDetectorOptions faceDetectorOptions = FaceDetectorOptions(
enableTracking: true,
enableLandmarks: true,
enableContours: false,
enableClassification: true,
minFaceSize: 0.1,
mode: FaceDetectorMode.accurate,
);
final FaceDetector faceDetector =
FirebaseVision.instance.faceDetector(faceDetectorOptions);
faceDetector.processImage(visionImage);
final List<Face> faces = await faceDetector.processImage(visionImage);
print('Number of Faces: ${faces.length}');
for (Face face in faces) {
var boundingBox = face.boundingBox;
final double rotY = face.headEulerAngleY;
final double rotZ = face.headEulerAngleZ;
print('Face Rotation: $rotY, $rotZ');
if (face.trackingId != null) {
final int id = face.trackingId;
print('Face: $id');
}
final FaceLandmark leftEar = face.getLandmark(FaceLandmarkType.leftEar);
if (leftEar != null) {
var leftEarPos = leftEar.position;
print('left ear position: ${leftEarPos}');
}
if (face.smilingProbability != null) {
var smileProb = face.smilingProbability;
print('Smile: $smileProb');
}
if (face.leftEyeOpenProbability != null) {
var leftEyeOpen = face.leftEyeOpenProbability;
print('Left eye open: $leftEyeOpen');
}
if (face.rightEyeOpenProbability != null) {
var rightEyeOpen = face.rightEyeOpenProbability;
print('Right eye open: $rightEyeOpen');
}
}
}
}
Did you try deepface package for python? It will access your web cam and apply face recognition in real-time.
#!pip install deepface
from deepface import DeepFace
DeepFace.stream("C:/my_db")
Here, you need to store facial image database in C:/my_db folder.