how can i using image_cropper i have this error? - flutter

photo of errorList item
class UserImagePicker extends StatefulWidget {
#override
_UserImagePickerState createState() => _UserImagePickerState();
}
class _UserImagePickerState extends State<UserImagePicker> {
final picker = ImagePicker();
File _imageFile;
String _currentImageUrl;
// Future pickImage() async {
// final pickedFile = await picker.getImage(source: ImageSource.gallery);
// setState(() {
// _imageFile = File(pickedFile.path);
// });
// }
Future uploadImage(BuildContext context) async {
String fileName = basename(_imageFile.path);
StorageReference storageReference =
FirebaseStorage.instance.ref().child('images/$fileName');
StorageUploadTask uploadTask = storageReference.putFile(_imageFile);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
taskSnapshot.ref.getDownloadURL().then((val) {
print('Dome:$val');
setState(() {
_currentImageUrl = val;
});
});
}
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return Scaffold(
backgroundColor: customColor,
body: StreamBuilder<Users>(
stream: DatabaseServices(userId: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
Users userData = snapshot.data;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Stack(
children: [
Container(
height: 150,
width: 150,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
spreadRadius: 2,
blurRadius: 10,
color: Colors.black.withOpacity(0.1),
offset: Offset(0, 10),
),
],
border: Border.all(
color: Colors.white,
width: 3,
),
),
child: CircleAvatar(
radius: 55,
backgroundColor: Colors.white,
child: ClipOval(
child: SizedBox(
height: 150,
width: 150,
child: (_imageFile != null)
? FileImage(
_imageFile,
)
: Image(
image: NetworkImage(
UserData.userImageUrl,
),
fit: BoxFit.cover,
),
),
),
),
),
Positioned(
bottom: 0,
right: 0,
child: GestureDetector(
onTap: () {
_showPickOptionsDialog(context);
},
child: Container(
height: 35,
width: 35,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: customColor,
border: Border.all(
color: Colors.white,
width: 2,
),
),
child: Icon(
Icons.edit,
color: Colors.white,
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
color: Colors.white,
child: Text(
getTranslated(context, 'save'),
style: AppTheme.heading.copyWith(
color: customColor,
),
),
onPressed: () {
DatabaseServices(userId: user.uid).updateUserData(
userData.phoneNumber,
userData.name,
userData.email,
_currentImageUrl ?? userData.userImageUrl,
);
DBHelper.saveUserSingIn(true);
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => Home(),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(
width: 1,
color: Colors.white,
),
),
child: Text(
getTranslated(context, 'skip'),
style: AppTheme.heading.copyWith(
color: Colors.white,
),
),
onPressed: () {
DBHelper.saveUserSingIn(true);
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => Home(),
),
);
},
),
),
],
),
],
),
);
} else {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
}
},
),
);
}
_loadPicker(ImageSource source, BuildContext context) async {
// ignore: deprecated_member_use
File picked = await ImagePicker.pickImage(source: source);
if (picked != null) {
_cropImage(picked, context);
}
Navigator.of(context).pop();
}
_cropImage(File picked, BuildContext context) async {
File cropped = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
statusBarColor: Colors.red,
toolbarColor: Colors.red,
toolbarTitle: "Crop Image",
toolbarWidgetColor: Colors.white,
),
sourcePath: picked.path,
aspectRatioPresets: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio16x9,
CropAspectRatioPreset.ratio4x3,
],
maxWidth: 800,
);
if (cropped != null) {
setState(() {
_imageFile = cropped;
uploadImage(context);
});
}
}
void _showPickOptionsDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text("Pick from Gallery"),
onTap: () {
_loadPicker(ImageSource.gallery, context);
},
),
ListTile(
title: Text("Take a pictuer"),
onTap: () {
_loadPicker(ImageSource.camera, context);
},
)
],[enter image description here][1]
),
),
);
}
}
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vanillia">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"/>
error:
in photo
PlatformException (PlatformException(error, Unable to find explicit activity class {com.example.vanillia/c.e.a.j}; have you declared this activity in your AndroidManifest.xml?, null, android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.vanillia/c.e.a.j}; have you declared this activity in your AndroidManifest.xml?

Related

Image should be upload only that column which is clicked not in all and also explode blank image box

The image should be uploaded only to that column which is clicked not in all.
I write a code where I have columns in Gridviw and each column has the property to upload the image. The image will be uploaded on that column which is clicked but in my code when I click any column to upload an image it uploads in all columns. so I want to upload an image on a particular column that I click.
also when I upload an image and add a new column it adds a new box with an image, not blank box.
so please help me to do this.
Here is my code:-
import 'package:flutter/material.dart';
import 'package:/utils/widget_functions.dart';
import 'package:******/custom/BorderIcon.dart';
import 'package:******/screens/Relation.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
class Photos extends StatefulWidget {
var usrid;
Photos({Key? key, #required this.usrid}) : super(key: key);
#override
_Photos createState() => _Photos();
}
class _Photos extends State<Photos>{
PickedFile? _imageFile;
final String uploadUrl = 'https://api.imgur.com/3/upload';
final ImagePicker _picker = ImagePicker();
Future<String?> uploadImage(filepath, url) async {
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(await http.MultipartFile.fromPath('image', filepath));
var res = await request.send();
return res.reasonPhrase;
}
Future<void> retriveLostData() async {
final LostData response = await _picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
_imageFile = response.file;
});
} else {
print('Retrieve error ${response.exception?.code}');
}
}
int counter = 0;
//List<Widget> _list = List<Widget>();
List<Widget> _list = <Widget> [];
List<PickedFile?> _images = [];
#override
void initState() {
for (int i = 0; i < 2; i++) {
Widget child = _newItem(i);
_list.add(child);
};
}
void on_Clicked() {
Widget child = _newItem(counter);
setState(
() => _list.add(child),
);
}
Widget _previewImage(int i) {
final _imageFile = this._imageFile;
if (_imageFile != null) {
return
SizedBox(
//width: 300,
height: 100,
child: Center(child:
ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.file(
File(
_imageFile.path,
),
height: 80,
)
),
),
);
} else {
return InkWell(
onTap: () => _pickImage(i),
child: SizedBox(
//width: 300,
height: 100,
child: Center(child:
Icon(
Icons.image,
color: Color(0xffcccccc),
size: 60,
),
),
),
);
}
}
Widget _newItem(int i) {
Key key = new Key('item_${i}');
Column child = Column(
key: key,
children: [
Stack(
children: [
Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xffa1a1a1),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: _previewImage(i),
),
Positioned(
top: 9,
right: 9,
child: InkWell(
onTap: () => _removeItem(i),
child: SvgPicture.asset(
width: 20,
'assets/images/close.svg',
height: 20,
),
),
)
]
),
]
);
counter++;
return child;
}
void _removeItem(int i) {
print("====remove $i");
print('===Removing $i');
setState(() => _list.removeAt(i));
}
void _pickImage( int i ) async {
try {
final pickedFile = await _picker.getImage(source: ImageSource.gallery);
setState(() {
_imageFile = pickedFile;
_images.add(pickedFile);
});
} catch (e) {
//print("Image picker error ${e!}");
print("Image picker error");
}
}
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
var regID = widget.usrid;
return Theme(
data: ThemeData().copyWith(
dividerColor: Colors.transparent,
backgroundColor: Colors.transparent
),
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
leading: Builder(
builder: (BuildContext context) {
return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
child: IconButton(
icon: const Icon(
Icons.arrow_back_ios_outlined,
color: Colors.black,
),
onPressed: () { Navigator.pop(context); },
),
);
},
),
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
//colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
colors: [Colors.white, Colors.white]
),
),
width: size.width,
height: size.height,
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
addVerticalSpace(10),
Padding(
padding: sidePadding,
child: const Text(
'Add Your Photos',
style: TextStyle(
color: Colors.black,
fontSize: 20,
),),
),
addVerticalSpace(30),
Expanded(
child: Padding(
padding: sidePadding,
child: Column(
children: [
Expanded(
child: GridView(
//padding: const EdgeInsets.all(8.0),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10.0,
mainAxisSpacing: 15,
//childAspectRatio: 2/1,
),
// children: List.generate(_list.length, (index) {
// //generating tiles with people from list
// return _newItem(index);
// },
// ),
children: List.generate(_list.length + 1,
(index) => index == _list.length ?
InkWell(
onTap: () => on_Clicked(),
child: Column(
children: [
Stack(
children: const [
Card(
elevation: 0,
color: Color(0xff8f9df2),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xff8f9df2),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: SizedBox(
//width: 300,
height: 100,
child: Center(child:
Icon(
Icons.add,
color: Colors.white,
size: 80.0,
),
),
),
)
]
),
]
),
) :
_newItem(index)),
)
)
],
),
)
),
],
),
],
)
),
),
persistentFooterButtons:[
Padding(
padding: EdgeInsets.fromLTRB(18, 0, 18, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
ElevatedButton.icon( // <-- ElevatedButton
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(
Icons.arrow_back_ios_outlined,
size: 15.0,
color:Colors.white,
),
label: const Text(
'Back',
style: TextStyle(
fontSize: 20,
),
),
style: ElevatedButton.styleFrom(
primary: Color(0xffFDA766),
minimumSize: const Size(100, 49),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0),)
),
),
Directionality(
textDirection: TextDirection.rtl,
child: ElevatedButton.icon( // <-- ElevatedButton
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Relation(usrid:regID)),
);
},
icon: const Icon(
Icons.arrow_back_ios_outlined,
size: 15.0,
color:Colors.white,
),
label: const Text(
'Next',
style: TextStyle(
fontSize: 20,
),
),
style: ElevatedButton.styleFrom(
primary: Color(0xffFDA766),
minimumSize: const Size(100, 49),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0),)
),
),
),
]
),
),
]
),
);
}
}
And here is my output:- this is the output image before image upload
After image upload:- and this image after upload where it uploads all two columns
Please help me with how I solve this.

Field '_image' has not been initialized in flutter

I wastrying image upload in flutter using imagepicker. While I was choose image the image cant display in one container. I was no error in error console. But the error was"Field '_image' has not been initialized. I am confused in flutter. Please he me guys
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
File? _image;
final picker = ImagePicker();
TextEditingController namecontroller = TextEditingController();
Future chooseimage() async {
var pickedImage = await picker.pickImage(source: ImageSource.gallery);
setState(() {
//_image = File(pickedImage!.path);
_image = File(pickedImage!.path);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Upload Image"),
),
body: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: chooseimage,
child: Text("Select Image"),
style: ElevatedButton.styleFrom(primary: Colors.green),
),
TextField(
controller: namecontroller,
decoration: InputDecoration(label: Text("Name")),
),
SizedBox(
height: 30.0,
),
ElevatedButton(
onPressed: () {},
child: Text("Upload"),
style: ElevatedButton.styleFrom(primary: Colors.blue),
),
Container(
child: _image == null
? Text('No Image Select')
: Image.file(_image!),
),
],
),
),
),
);
}
}
///You can take a reference through this code hope this will work for you. Thanks
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:provider/provider.dart';
import 'package:traveling/Provider/EmployeeProvider/EmployeeProfileProvider.dart';
import 'package:traveling/helpers/AppColors.dart';
///To get the crop value creating a class
enum AppState {
free,
picked,
cropped,
}
class EmployeeProfile extends StatefulWidget {
final bool leadingIcon;
final number;
final cardName;
EmployeeProfile(
{Key? key, required this.leadingIcon, this.number, this.cardName})
: super(key: key);
#override
_EmployeeProfileState createState() => _EmployeeProfileState();
}
class _EmployeeProfileState extends State<EmployeeProfile>
with TickerProviderStateMixin {
EmployeeProfileProvider? _provider;
///controller widget used in Spinkit plugin to show loading process
animationControllerField(){
AnimationController animationController =AnimationController(
vsync: this, duration: const Duration(milliseconds: 900));
}
bool? visible;
double? _width;
File? _image;
var url;
late AppState state;
final picker = ImagePicker();
///pop-up to choose camera gallery while uploading image
Future<void> _showChoiceDialog(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
"Choose option",
style: TextStyle(color: AppColors.hotelListDarkBlue),
),
content: SingleChildScrollView(
child: ListBody(
children: [
Divider(
height: 1,
color: AppColors.baseLightBlueColor,
),
ListTile(
onTap: () {
Navigator.pop(context, _pickImage(ImageSource.gallery,context));
},
title: Text(
"Gallery",
style: TextStyle(color: AppColors.hotelListDarkBlue),
),
leading: Icon(
Icons.account_box,
color: AppColors.baseLightBlueColor,
),
),
Divider(
height: 1,
color: AppColors.baseLightBlueColor,
),
ListTile(
onTap: () {
Navigator.pop(context, _pickImage(ImageSource.camera,context));
},
title: Text(
"Camera",
style: TextStyle(color: AppColors.hotelListDarkBlue,),
),
leading: Icon(
Icons.camera,
color: AppColors.baseLightBlueColor,
),
),
],
),
),
);
});
}
///crop image selecting by the user
Future<Null> _cropImage() async {
File? croppedFile = await ImageCropper.cropImage(
sourcePath: _image!.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
]
: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio5x3,
CropAspectRatioPreset.ratio5x4,
CropAspectRatioPreset.ratio7x5,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: AppColors.baseLightBlueColor,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Cropper',
));
if (croppedFile != null) {
_image = croppedFile;
setState(() {
state = AppState.cropped;
});
///to get upload image
url = await _provider!.setUserUpdatedImageInfo(_image!, );
setState(() {
///to set the image
_provider!.currentLoggedInUser!.image = url;
});
}
}
///icon change while user edit image
Widget _buildButtonIcon() {
if (state == AppState.free)
return Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
);
else if (state == AppState.picked)
return Icon(Icons.crop,color: AppColors.popUpBlueColor,
size: 20,);
else if (state == AppState.cropped)
return Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
);
else
return Container();
}
#override
void initState() {
// TODO: implement initState
super.initState();
print("initState called");
state = AppState.free;
_provider = EmployeeProfileProvider();
_provider!.getUserInfo();
}
///this widget is the main widget and it is used for building a UI in the app.
#override
Widget build(BuildContext context) {
_width = MediaQuery.of(context).size.width;
return ChangeNotifierProvider<EmployeeProfileProvider?>(
create: (context) => _provider!,
child: Consumer<EmployeeProfileProvider?>(
builder: (context, provider, child) {
return provider!.currentLoggedInUser==null?
Material(
color: AppColors.white,
child: Center(
child:
SpinKitCubeGrid(
color: AppColors.baseLightBlueColor,
size: 50.0,
controller:animationControllerField()
),
),
):Container(
width: _width!,
color: AppColors.white,
child: Stack(
children: [
Column(
children: [
Material(
color: AppColors.baseLightBlueColor,
elevation: 15,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.only(bottomRight: Radius.circular(30)),
),
child: Container(
height: 180,
decoration: BoxDecoration(
color: AppColors.baseLightBlueColor,
// AppColors.blue,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(30)),
),
),
),
],
),
Positioned(
top: 80,
child:
Stack(
children: [
Container(
height: 150,
width: _width,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CachedNetworkImage(
filterQuality: FilterQuality.high,
maxHeightDiskCache: 100,
fit: BoxFit.cover,
imageUrl: provider.currentLoggedInUser!.image.toString(),
imageBuilder: (context, imageProvider) => Container(
height: 120,
width: 120,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: imageProvider, fit: BoxFit.cover),
border: Border.all(
color: AppColors.white, width: 2.0),
),
),
placeholder: (context, url) =>
const CircularProgressIndicator(),
errorWidget: (context, url, error) => Container(
height: 120,
width: 120,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
image:DecorationImage(
fit: BoxFit.cover,
image: AssetImage('assets/managerPicture.jpeg')),
border: Border.all(
color: AppColors.white, width: 2.0),
),
),
fadeOutDuration: const Duration(seconds: 1),
fadeInDuration: const Duration(seconds: 3),
),
],
),
),
Positioned(
top: 60,
right: 0,
left: 100,
bottom: 0,
child: GestureDetector(
onTap: () {
if (state == AppState.free)
_showChoiceDialog(context);
else if (state == AppState.picked)
_cropImage();
else if (state == AppState.cropped) _showChoiceDialog(context);
},
child: Container(
height: 10,
width: _width,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Container(
height: 35,
width: 35,
decoration: BoxDecoration(
color:
AppColors.profiePicBackground,
borderRadius:
BorderRadius.circular(60),
),
child: ClipRRect(
borderRadius:
BorderRadius.circular(60.0),
child: _buildButtonIcon(),
/*Icon(
MdiIcons.squareEditOutline,
color: AppColors.popUpBlueColor,
size: 20,
),*/
),
),
],
),
),
),
)
],
)
),
Positioned(
top: 40,
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(left: 8, right: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
widget.leadingIcon == true
? Align(
alignment: Alignment.topLeft,
child: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Icon(
MdiIcons.arrowLeft,
color: Colors.white,
)),
)
: Container(),
],
),
)),
],
),
);
}));
}
///ImageSource: Camera and Gallery.
Future<Null> _pickImage(ImageSource source,context) async {
final pickedImage = await ImagePicker().pickImage(source: source);
_image = pickedImage != null ? File(pickedImage.path) : null;
if (_image != null) {
setState(() {
state = AppState.picked;
});
}
}
}
class EmployeeProfileProvider extends ChangeNotifier {
late bool _isInfoEditable;
FirebaseFirestore? fireStoreInstance;
EmployeeProfileModel? _userData;
// EmployeeMyExpenseReport ? _employeeMyExpenseReport;
///to update the employee profile image
Future<String?> setUserUpdatedImageInfo(File _image, ) async {
var data= await EmployeeServices.getInstance().uploadImageToFirebase(_image, );
notifyListeners();
return data;
}
///to update Personal details of employee
EmployeeProfileModel? get getUploadedImage => _userData;
#override
void dispose() {
//print("Provider disposed called");
super.dispose();
}
//upload employee image on firebase
String ?url;
Future <String?>uploadImageToFirebase(File _image) async {
User? currentUser = FirebaseAuth.instance.currentUser;
String fileName = basename(_image.path);
firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
.ref().child('uploads')
.child('/$fileName');
final metadata = firebase_storage.SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'picked-file-path': fileName});
firebase_storage.UploadTask uploadTask;
uploadTask = ref.putFile(io.File(_image.path), metadata);
//String ?url;
await uploadTask.whenComplete(() async {
url = await uploadTask.snapshot.ref.getDownloadURL();
});
Future.value(uploadTask)
.then((value) => {
print("Upload file path ${value.ref.fullPath}"),
FirebaseFirestore.instance.collection(FirestoreCollections.employees).doc(currentUser!.uid).update({'image': '$url'}),
})
.onError((error, stackTrace) =>
{
print("Upload file path error ${error.toString()} ")}
);
return url;
}
}

how to do pdf thumbnails in flutter?

I'm developing a pdf app with flutter. The thing I want to say is how I should do with pdf's thumbnails. I mean when the users open the application the second time after installing, I want to show the screen of pdf's thumbnails instantly not loading again. How should I do? Save images locally or any solution?. The code is below.
import 'dart:io';
import 'dart:typed_data';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'constant.dart';
import 'file_picker.dart';
import 'icon_button.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:pdf_image_renderer/pdf_image_renderer.dart';
import 'package:path_provider_extention/path_provider_extention.dart';
import 'file_manager.dart';
import 'save_screen.dart';
import 'sorting.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<FileSystemEntity> pdffile;
List<Uint8List> pdfimage = [];
BannerAd bannerAds;
AppOpenAd openAd;
bool isAdsload = false;
void initState() {
super.initState();
initBannerAds();
loadAd();
getFile();
}
void dispose() {
super.dispose();
bannerAds.dispose;
}
loadAd() {
AppOpenAd.load(
adUnitId: 'ca-app-pub-4233045876357680/8169845508',
request: const AdRequest(),
adLoadCallback: AppOpenAdLoadCallback(onAdLoaded: (ad) {
print('ad is loaded');
openAd = ad;
openAd.show();
}, onAdFailedToLoad: (error) {
print('ad failed to load $error');
}),
orientation: AppOpenAd.orientationPortrait);
}
initBannerAds() {
bannerAds = BannerAd(
size: AdSize.banner,
adUnitId:'ca-app-pub-4233045876357680/9259518166',
listener: BannerAdListener(
onAdLoaded: (ad) {
setState(() {
isAdsload = true;
});
},
onAdFailedToLoad: (ad, error) {
print(error.toString());
},
),
request: AdRequest(),
);
bannerAds.load();
}
getFile() async {
await Permission.storage.request();
List<StorageInfo> storageInfo = await PathProviderEx.getStorageInfo();
var root = storageInfo[0].rootDir; //storageInfo[1] for SD card, geting the root
// directory
var fm = FileManager(root: Directory(root)); //
pdffile = await fm.filesTree(
excludedPaths: [
"/storage/emulated/0/Android"
],
extensions: [
"pdf",
],
sortedBy: FlutterFileUtilsSorting.Alpha,
//optional, to filter files, list only pdf files
);
print(pdffile);
for (int index = 0; index < pdffile.length; index++) {
final document = await PdfImageRendererPdf(path: pdffile[index].path);
await document.open();
// open a page from the pdf document using the page index
await document.openPage(pageIndex: 0);
// get the render size after the page is loaded
final size = await document.getPageSize(pageIndex: 0);
// get the actual image of the page
final pageImage = await document.renderPage(
pageIndex: 0,
x: 0,
y: 0,
width: size.width,
// you can pass a custom size here to crop the image
height: size.height,
// you can pass a custom size here to crop the image
scale: 1,
// increase the scale for better quality (e.g. for zooming)
background: Colors.white,
);
await document.closePage(pageIndex: 0);
document.close();
setState(() {
pdfimage.add(pageImage);
});
print(pdfimage);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
drawer: Drawer(
child: ListView(
padding: EdgeInsets.all(5),
children: [
DrawerHeader(decoration: BoxDecoration(color: Colors.cyan), child: Text("Jensen
Pdf Viewer", style: fontStyle)),
ListTile(
leading: iconButton(icons: Icons.folder_open, onPress: () {}),
title: Text('Pick Files', style: styles),
onTap: () {
FilePickers().PickFile();
}),
ListTile(
leading: iconButton(icons: Icons.bug_report, onPress: () {}),
title: Text('Report Bug', style: styles),
onTap: () async {
await Future.delayed(const Duration(seconds: 1), () {
Get.toNamed('fourth');
});
})
],
)),
appBar: AppBar(
title: Text('Jensen Pdf Viewer', style: fontStyle),
),
body: pdfimage != null
? Container(
child: Column(
children: [
Expanded(
child: Container(
margin: EdgeInsets.only(left: 3, right: 3),
decoration: BoxDecoration(
color: Color(0xFFA9C9CC),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(4, 3), // changes position of shadow
),
],
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40),
)),
child: Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(4),
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () async {
await Future.delayed(const Duration(milliseconds: 200), () {
Get.toNamed('second', arguments: '${pdffile[index].path}');
});
},
child: Card(
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Container(
padding: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.8,
decoration: BoxDecoration(
image: DecorationImage(image: MemoryImage(pdfimage[index]), fit: BoxFit.fill),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
),
));
},
itemCount: pdfimage.length,
itemWidth: 250.0,
layout: SwiperLayout.STACK,
))),
),
SizedBox(height: 10),
Container(
child: Text("Categories", style: fontStyle),
),
SizedBox(height: 10),
Expanded(
child: ListView.builder(
itemCount: pdfimage.length,
itemBuilder: (context, index) {
String fileName = pdffile[index].path.split('/').last;
return Card(
color: context.theme.scaffoldBackgroundColor,
elevation: 10,
margin: EdgeInsets.all(5),
child: Container(
margin: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
InkWell(
onTap: () async {
await Future.delayed(const Duration(milliseconds: 200), () {
Get.toNamed('second', arguments: '${pdffile[index].path}');
});
},
child: Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.25,
maxHeight: MediaQuery.of(context).size.width * 0.21,
),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0, 3), // changes position of shadow
),
],
borderRadius: BorderRadius.all(Radius.circular(10)),
image: DecorationImage(image: MemoryImage(pdfimage[index]), fit: BoxFit.fill),
))),
SizedBox(width: 10),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.4,
margin: EdgeInsets.only(left: 20),
child: Text(
fileName,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis,
style: styles,
maxLines: 1,
)),
),
iconButton(
icons: Icons.forward,
onPress: () async {
await Future.delayed(const Duration(milliseconds: 200), () {
Get.toNamed('second', arguments: '${pdffile[index].path}');
});
}),
],
),
));
// }))
}),
),
],
),
)
: Container(child: Center(child: Container(margin: EdgeInsets.all(20), child: Text("There is no Pdf in Internal Storage. Tap Menu Icon", style: fontStyle)))),
bottomNavigationBar: isAdsload
? Container(
width: bannerAds.size.width.toDouble(),
height: bannerAds.size.height.toDouble(),
child: AdWidget(
ad: bannerAds,
),
)
: null,
),
);
}
}
I'm developing a package to show thumbnails for PDF files.
pdf_thumbnail
You can simply use it as a widget.
PdfThumbnail.fromFile(pdfFile)

flutter PageView onPageChanged with setstate

i am working with PageView but if i swipe to change it will change the page But if i put onPageChanged to setState for me to get to current index it will not change the page.
here is my code
int _indicatorsPages = 0;
final PageController controller =
PageController(initialPage: 0);
change(int page) {
setState(() {
_indicatorsPages = page;
}); }
code from build
Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
leading: Row(
children: [
SizedBox(
width: 10,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SettingsFMC(),
),
);
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 1, blurRadius: 2,
offset: Offset(0, 3), // i change position of shadow
),
],
),
child: Center(
child: Icon(
FontAwesomeIcons.slidersH,
size: 20,
color: Colors.black,
)),
),
),
],
),
elevation: 0,
backgroundColor: Colors.transparent,
actions: [
GestureDetector(
onTap: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Actitvities(),
),
);
final doc = await firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.get();
if (doc.docs.isNotEmpty) {
firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.get()
.then((value) {
value.docs.forEach((doc) {
doc.reference.update({'seen': true});
});
});
}
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
spreadRadius: 1, blurRadius: 2,
offset: Offset(0, 3), // i change position of shadow
),
],
),
child: StreamBuilder(
stream: firestore
.collection('feeds')
.doc(auth.currentUser.uid)
.collection('feedsItems')
.where('seen', isEqualTo: false)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
));
}
if (snapshot.data.docs.isEmpty) {
return Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
));
}
return Badge(
animationType: BadgeAnimationType.scale,
badgeContent: Text('${snapshot.data.docs.length}'),
position: BadgePosition.topStart(),
showBadge: true,
child: Center(
child: Icon(
Icons.notifications_none_outlined,
size: 20,
color: Colors.black,
)),
);
}),
),
),
SizedBox(
width: 10,
),
],
),
extendBodyBehindAppBar: true,
body: userProfileLoading
? Center(
child: CircularProgressIndicator(),
)
: Stack(
children: [
Container(
height: MediaQuery.of(context).size.height / 1.6,
child: StreamBuilder(
stream: firestore
.collection('Image')
.doc(widget.viewId)
.collection('Photos')
.orderBy('timestap', descending: false)
.snapshots(),
builder: (context, AsyncSnapshot snapshot) {
int idx = 0;
List<Widget> list = [];
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (!snapshot.hasData) {
return Center(
child: Text("No image Found, Add images"),
);
} else {
if (snapshot.hasError) {
return Center(child: Text("fetch error"));
} else {
for (int i = 0;
i < snapshot.data.docs.length;
i++) {
// print('the lent of the document is $idx');
list.add(
FullScreenWidget(
child: Hero(
tag: "customTag",
child: Image.network(
snapshot.data.docs[idx]
.data()['picture'],
fit: BoxFit.cover,
),
),
),
);
idx++;
}
return Stack(
children: [
PageView(
key: _key,
scrollDirection: Axis.horizontal,
controller: controller,
onPageChanged: change,
// onImageChange: (pre, current) {
// print('this current : $current');
// setState(() {
// indicatorsPages = current;
// });
// },
// boxFit: BoxFit.cover,
// autoplay: false,
// animationCurve: Curves.fastOutSlowIn,
// animationDuration:
// Duration(milliseconds: 1000),
// dotIncreasedColor: Colors.orange,
// dotBgColor: Colors.transparent,
// dotPosition: DotPosition.bottomCenter,
// dotVerticalPadding:
// MediaQuery.of(context).size.height / 15,
//showIndicator: false,
// indicatorBgPadding: 7.0,
children: list,
),
Positioned(
right:
MediaQuery.of(context).size.width / 2,
bottom: 75,
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: Colors.white),
child: indicat.DotsIndicator(
dotsCount: list.length,
position: _indicatorsPages.toDouble(),
decorator: DotsDecorator(
color:
Colors.grey, // Inactive color
activeColor: Colors.black,
),
)),
)
],
);
}
}
}),
),
You are wrong. When you use pageView, it will call onPageChnaged function after page changed. If you want to change page programmatically, you should use pageView.animateToPage() function.
import 'package:flutter/material.dart';
class OnBoarding extends StatefulWidget {
#override
_OnBoardingState createState() => _OnBoardingState();
}
class _OnBoardingState extends State<OnBoarding> {
PageController controller;
int currentIndex = 0;
#override
void initState() {
controller = PageController();
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent[200],
body: Stack(
children: [
PageView(
onPageChanged: onchahged,
controller: controller,
children: [
Container(
child: Image.asset('assets/fierceninja.png'),
),
Container(
child: Image.asset('assets/ninja.png'),
),
Container(
child: Image.asset('assets/ninjahead.jpg'),
),
],
),
],
),
);
}
onchahged(int index) {
setState(() {
currentIndex = index;
});
}
}
Here's a complete example.

PhotoURL was called on null error in flutter [duplicate]

This question already has answers here:
What is a NoSuchMethod error and how do I fix it?
(2 answers)
Closed 2 years ago.
In my flutter project, i used CachedNetworkImageProvider, in which i passed photo url, but it is showing me an error, that it is called on null. Can anyone help me please? Check out line 158. If you think, there is nothing wrong in this part, and some other widget is causing the error, (that are made by me), then please tell me, i will provide you that. Please help me. I am new to this thing.
Here's the exception -
The getter 'photoUrl' was called on null.
Receiver: null
Tried calling: photoUrl
The relevant error-causing widget was:
Upload file:///C:/Users/Hp/AndroidStudioProjects/social_app/lib/pages/home.dart:117:11
Here's the code -
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:social_app/models/users.dart';
class Upload extends StatefulWidget {
final User currentUser;
Upload({this.currentUser});
#override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> {
File file;
handleTakePhoto() async {
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 960, maxHeight: 675);
// ImagePicker imagePicker;
// PickedFile pickedFile = await imagePicker.getImage(source: ImageSource.camera, maxHeight: 675, maxWidth: 960);
// File file = File(pickedFile.path);
setState(() {
this.file = file;
});
}
handleChooseFromGallery() async{
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
this.file = file;
});
// ImagePicker imagePicker;
// PickedFile pickedFile = await imagePicker.getImage(source: ImageSource.gallery);
// File file = File(pickedFile.path);
// setState(() {
// this.file = file;
// });
}
selectImage(parentContext) {
return showDialog(
context: parentContext,
builder: (context) {
return SimpleDialog(
title: Text('Create Post'),
children: <Widget>[
SimpleDialogOption(
child: Text('Click Photo'),
onPressed: handleTakePhoto,
),
SimpleDialogOption(
child: Text('Import from Gallery'),
onPressed: handleChooseFromGallery,
),
SimpleDialogOption(
child: Text('Cancel'),
onPressed: () => Navigator.pop(context),
),
],
);
}
);
}
Container buildSplashScreen() {
return Container(
color: Colors.black54,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SvgPicture.asset('assets/images/upload.svg', height: 300.0,),
Padding(
padding: EdgeInsets.only(top: 40.0),
child: RaisedButton(
padding: EdgeInsets.all(10.0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
child: Text(
'Upload Image',
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
),
color: Colors.blueGrey[600],
onPressed: () => selectImage(context),
),
),
],
),
);
}
clearImage() {
setState(() {
file =null;
});
}
Scaffold buildUploadForm() {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white70,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black,),
onPressed: clearImage,
),
title: Center(
child: Text(
'Caption Post',
style: TextStyle(
color: Colors.black,
),
),
),
actions: [
FlatButton(
onPressed: () => print('Pressed'),
child: Text(
'Post',
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
),
],
),
body: ListView(
children: <Widget>[
Container(
height: 220.0,
width: MediaQuery.of(context).size.width * 0.8,
child: Center(
child: AspectRatio(
aspectRatio: 16/9,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(file),
),
),
),
),
),
),
Padding(
padding: EdgeInsets.only(top: 10.0),
),
ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(widget.currentUser.photoUrl),
),
title: Container(
width: 250.0,
child: TextField(
decoration: InputDecoration(
hintText: "Write a caption..",
border: InputBorder.none,
),
),
),
),
Divider(
),
ListTile(
leading: Icon(
Icons.pin_drop,
color: Colors.blue,
size: 36.0,
),
title: Container(
width: 250.0,
child: TextField(
decoration: InputDecoration(
hintText: 'Search a location...',
border: InputBorder.none,
),
),
),
),
Container(
width: 200.0,
height: 100.0,
alignment: Alignment.center,
child: RaisedButton.icon(
label: Text(
'Use current location...',
style: TextStyle(
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Colors.blue,
onPressed: () => print('Get user location'),
icon: Icon(
Icons.my_location,
color: Colors.white,
),
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return file == null ? SafeArea(
child: Scaffold(
backgroundColor: Colors.black45,
body: buildSplashScreen(),
),
) : buildUploadForm();
}
}
home page -
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:social_app/pages/activity_feed.dart';
import 'package:social_app/pages/create_account.dart';
import 'package:social_app/pages/profile.dart';
import 'package:social_app/pages/search.dart';
import 'package:social_app/pages/timeline.dart';
import 'package:social_app/pages/upload.dart';
import 'package:social_app/widgets/header.dart';
import 'package:social_app/models/users.dart';
final GoogleSignIn googleSignIn = GoogleSignIn();
final usersRef = FirebaseFirestore.instance.collection('users');
final DateTime timeStamp = DateTime.now();
User currentUser;
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isAuth = false;
PageController pageController;
int pageIndex=0;
#override
void initState(){
super.initState();
pageController = PageController(initialPage: 0);
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
},
onError: (error) {
print("Error in signing in : $error");
});
googleSignIn.signInSilently(suppressErrors: false).then((account){
handleSignIn(account);
}).catchError((error){
print("Error in signing in : $error");
});
}
handleSignIn(GoogleSignInAccount account) {
if (account != null) {
createUserInFirestore();
setState(() {
isAuth = true;
});
}
else {
setState(() {
isAuth = false;
});
}
}
createUserInFirestore() async{
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.doc(user.id).get();
if(!doc.exists) {
final username = await Navigator.push(context, MaterialPageRoute(builder: (context) => CreateAccount()));
usersRef.doc(user.id).set({
"id" : user.id,
"username" : username,
"photoUrl" : user.photoUrl,
"email" : user.email,
"displayName" : user.displayName,
"bio" : "",
"timeStamp" : timeStamp,
});
}
}
#override
void dispose() {
pageController.dispose();
super.dispose();
}
login() {
googleSignIn.signIn();
}
logout() {
googleSignIn.signOut();
}
onPageChanged(int pageIndex) {
setState(() {
this.pageIndex = pageIndex;
});
}
onTap(int pageIndex) {
pageController.animateToPage(
pageIndex,
duration: Duration(milliseconds: 250),
curve: Curves.easeInOut,
);
}
Scaffold buildAuthScreen(){
return Scaffold(
body: PageView(
children: <Widget>[
//Timeline(),
RaisedButton(
onPressed: logout,
child: Text('logout'),
),
Search(),
Upload(currentUser: currentUser),
ActivityFeed(),
Profile(),
],
controller: pageController,
onPageChanged: onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: CupertinoTabBar(
backgroundColor: Colors.black,
currentIndex: pageIndex,
onTap: onTap,
activeColor: Colors.white,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home_filled)),
BottomNavigationBarItem(icon: Icon(Icons.search)),
BottomNavigationBarItem(icon: Icon(Icons.add_box_outlined)),
BottomNavigationBarItem(icon: Icon(Icons.favorite_border)),
BottomNavigationBarItem(icon: Icon(Icons.account_circle)),
],
),
);
// return RaisedButton(
// onPressed: logout,
// child: Text('logout'),
// );
}
Scaffold buildUnauthScreen() {
return Scaffold(
appBar: header(context, titleText: 'Instagram'),
backgroundColor: Colors.black,
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Theme.of(context).primaryColor,
Colors.teal.withOpacity(1.0),
Colors.orange,
]
),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Technua',
style: GoogleFonts.gochiHand(
fontSize: 70.0,
color: Colors.white,
),
),
GestureDetector(
onTap: login,
child: Container(
height: 60.0,
width: 260.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/google_signin_button.png'),
fit: BoxFit.cover,
)
),
),
),
],
),
),
),
);
}
#override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : buildUnauthScreen();
}
}
You have created an optional named parameter currentUser in your StatefulWidget Upload. I think the user that you have passed in the Upload widget is null.
You have to check where are you calling the Upload widget from & then check whether the user is null or not.
However, if the currentUser is null, you can prevent the error by using null aware operator as follows:
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(
widget.currentUser?.photoUrl, // <-----
),
),
Your current user is null. You have to set a user in here:
final User currentUser;