how to do pdf thumbnails in flutter? - 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)

Related

Flutter : how to change text data by bottomSheet?

I want to change my text, after selecting by bottomsheet text is not changing when i am refreshing then my text is changing.
how to fix this issue.
This is my code.
import 'package:flutter/material.dart';
import '../../../Utils/GlobalColor/global_color.dart';
import '../../../Utils/GlobalTextStyles/global_text_styles.dart';
class NonVegPizzaPage extends StatefulWidget {
const NonVegPizzaPage({Key? key}) : super(key: key);
#override
State<NonVegPizzaPage> createState() => _NonVegPizzaPageState();
}
class _NonVegPizzaPageState extends State<NonVegPizzaPage> {
String itemSize = "Regular";
List itemSizes = [];
#override
void initState() {
super.initState();
itemSizes = [
{
"sizes": "Regular",
},
{
"sizes": "Medium",
},
{
"sizes": "Large",
},
];
}
sizeBottomSheet() {
showModalBottomSheet(
barrierColor: Colors.transparent,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
),
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState1) {
return Container(
decoration: BoxDecoration(
color: MyColor.whiteColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
),
boxShadow: [
BoxShadow(
color: MyColor.greyColor.withOpacity(0.8),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 0), // changes position of shadow
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding:
const EdgeInsets.only(left: 43.0, top: 10, bottom: 11),
child: Text(
"Select Size",
style: textStyleWith14500(MyColor.blackColor2),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: itemSizes.length,
itemBuilder: (_, index) {
return Padding(
padding: EdgeInsets.only(
top: 0,
),
child: InkWell(
onTap: () {
Navigator.pop(context);
setState1(() {
itemSize = itemSizes[index]["sizes"];
});
print(itemSize);
},
child: Container(
margin: EdgeInsets.only(left: 2, right: 2),
height: 36,
width: double.infinity,
color: itemSize == itemSizes[index]["sizes"]
? MyColor.lightBlueColor
: MyColor.whiteColor,
child: Padding(
padding:
const EdgeInsets.only(left: 43.0, top: 10),
child: Text(
"${itemSizes[index]["sizes"]}",
style:
textStyleWith12400(MyColor.blackColor3),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
);
}),
],
),
);
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: Column(crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("$itemSize"), // here
SizedBox(height: 20,),
InkWell(
onTap: () {
sizeBottomSheet();
},
child: Container(
color: Colors.red,
height: 44,
width: 150,
child: Center(child: Text("show bottomSheet")),
),
)
],
),
),
),
);
}
}
showModalBottomSheet is a future method, you can await to close it and then call setState to update the main ui.
sizeBottomSheet() async {
final result = await showModalBottomSheet(
....
onTap: () {
Navigator.pop(context, itemSizes[index]["sizes"]);
.......
//end of showModalBottomSheet
if (result != null) {
itemSize = result;
setState(() {});
}
Or you can do
child: InkWell(
onTap: () {
setState1(() {
itemSize = itemSizes[index]["sizes"];
});
setState(() {});//updating the parent
Navigator.pop(context);
},

Flutter ListView builder not updating with fresh data

I'm running a search filter function which retrieves players from a Floor DB. The functionality works fine and I can see through logs that the new player are returned, however my UI won't update which seems to be from the new list i assign not triggering a re-render.
Can anyone see what's wrong with my code?
import 'package:flutter/material.dart';
import '../database/LocalDatabase.dart';
import '../model/Player.dart';
class Pitch extends StatefulWidget {
const Pitch({super.key});
#override
_Pitch createState() => _Pitch();
}
class _Pitch extends State<Pitch> {
List<Player> playersList = <Player>[];
Offset positionOne = const Offset(100, 100);
Offset positionTwo = const Offset(200, 100);
#override
Widget build(BuildContext context) {
return Container(
constraints: BoxConstraints.expand(),
color: Colors.white,
child: Stack(
alignment: Alignment.center,
children: [
Image.asset("assets/images/pitch.png"),
Positioned(
left: positionOne.dx,
top: positionOne.dy,
child: Draggable(
feedback: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
childWhenDragging: Opacity(
opacity: 0,
child: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
),
child: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
onDragEnd: (details) {
setState(() {
positionOne = details.offset;
});
},
),
),
Positioned(
left: positionTwo.dx,
top: positionTwo.dy,
child: Draggable(
feedback: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
childWhenDragging: Opacity(
opacity: 0,
child: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
),
child: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
onDragEnd: (details) {
setState(() {
positionTwo = details.offset;
});
},
),
)
],
),
);
}
#override
void initState() {
super.initState();
// getPlayers().then((value) {
// debugPrint("playerfromdb: ${value[0].name}");
// });
}
Future<List<Player>> getPlayers() async {
final database =
await $FloorLocalDatabase.databaseBuilder('local_database.db').build();
final playerDao = database.playerDao;
final players = playerDao.getAllPlayers();
return players;
}
Widget playerImage(String imageUrl) {
return GestureDetector(
onTap: () => showDialog<void>(
context: context,
builder: (BuildContext context) => Dialog(
backgroundColor: Colors.white,
child: SizedBox(
height: 300,
width: 300,
child: Column(
children: [
const SizedBox(height: 24),
Container(
margin: const EdgeInsets.only(left: 16),
height: 48,
child: TextField(
decoration: const InputDecoration.collapsed(
hintText: 'Enter player name',
focusColor: Colors.transparent),
onChanged: (value) {
searchPlayers(value);
},
)),
const SizedBox(height: 24),
SizedBox(
height: 200,
child: ListView.builder(
itemCount: playersList.length,
itemBuilder: (context, index) {
return playerItem(playersList.elementAt(index));
}),
),
],
)))),
child: SizedBox(
width: 48,
height: 48,
child: Image.network(imageUrl),
));
}
Widget playerItem(Player? player) {
return Container(
height: 48,
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.only(left: 8, right: 8),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: const [BoxShadow(blurRadius: 8)]),
child: Row(
children: [
SizedBox(
height: 36,
width: 36,
child: Image.network(player?.playerImageUrl ?? "")),
const SizedBox(width: 8),
Text(player?.name ?? "")
],
),
);
}
Future<void> searchPlayers(String query) async {
final database = await $FloorLocalDatabase
.databaseBuilder('local_database.db')
.build();
final playerDao = database.playerDao;
// await List<Player> filteredPlayers =
playerDao.searchPlayers(query).then((value) {
setState(() => playersList = value);
debugPrint(value[0].name);
});
}
}
Because your put ListView.builder in Dialog it will create a new stack and a new stack can't rerender from another stack
You can change your code with create a new stateful widget for dialogs
import 'package:flutter/material.dart';
import '../database/LocalDatabase.dart';
import '../model/Player.dart';
class Pitch extends StatefulWidget {
const Pitch({super.key});
#override
_Pitch createState() => _Pitch();
}
class _Pitch extends State<Pitch> {
Offset positionOne = const Offset(100, 100);
Offset positionTwo = const Offset(200, 100);
#override
Widget build(BuildContext context) {
return Container(
constraints: BoxConstraints.expand(),
color: Colors.white,
child: Stack(
alignment: Alignment.center,
children: [
Image.asset("assets/images/pitch.png"),
Positioned(
left: positionOne.dx,
top: positionOne.dy,
child: Draggable(
feedback: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
childWhenDragging: Opacity(
opacity: 0,
child: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
),
child: playerImage(
"https://cdn.sofifa.net/players/158/023/22_120.png"),
onDragEnd: (details) {
setState(() {
positionOne = details.offset;
});
},
),
),
Positioned(
left: positionTwo.dx,
top: positionTwo.dy,
child: Draggable(
feedback: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
childWhenDragging: Opacity(
opacity: 0,
child: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
),
child: playerImage(
"https://cdn.sofifa.com/players/notfound_0_120.png"),
onDragEnd: (details) {
setState(() {
positionTwo = details.offset;
});
},
),
)
],
),
);
}
Widget playerImage(String imageUrl) {
return GestureDetector(
onTap: () => showDialog<void>(
context: context,
builder: (BuildContext context) => Dialog(
backgroundColor: Colors.white,
child: const PlayersDialog(),
),
),
child: SizedBox(
width: 48,
height: 48,
child: Image.network(imageUrl),
),
);
}
}
class PlayersDialog extends StatefulWidget {
const PlayersDialog({super.key});
#override
_PlayersDialog createState() => _PlayersDialog();
}
class _PlayersDialog extends State<PlayersDialog> {
List<Player> playersList = <Player>[];
Future<void> searchPlayers(String query) async {
final database =
await $FloorLocalDatabase.databaseBuilder('local_database.db').build();
final playerDao = database.playerDao;
// await List<Player> filteredPlayers =
playerDao.searchPlayers(query).then((value) {
setState(() => playersList = value);
debugPrint(value[0].name);
});
}
#override
Widget build(BuildContext context) {
return SizedBox(
height: 300,
width: 300,
child: Column(
children: [
const SizedBox(height: 24),
Container(
margin: const EdgeInsets.only(left: 16),
height: 48,
child: TextField(
decoration: const InputDecoration.collapsed(
hintText: 'Enter player name',
focusColor: Colors.transparent),
onChanged: (value) {
searchPlayers(value);
},
)),
const SizedBox(height: 24),
SizedBox(
height: 200,
child: ListView.builder(
itemCount: playersList.length,
itemBuilder: (context, index) {
return playerItem(playersList.elementAt(index));
},
),
),
],
),
);
}
Widget playerItem(Player? player) {
return Container(
height: 48,
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.only(left: 8, right: 8),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: const [BoxShadow(blurRadius: 8)]),
child: Row(
children: [
SizedBox(
height: 36,
width: 36,
child: Image.network(player?.playerImageUrl ?? "")),
const SizedBox(width: 8),
Text(player?.name ?? "")
],
),
);
}
#override
void initState() {
super.initState();
// getPlayers().then((value) {
// debugPrint("playerfromdb: ${value[0].name}");
// });
}
Future<List<Player>> getPlayers() async {
final database =
await $FloorLocalDatabase.databaseBuilder('local_database.db').build();
final playerDao = database.playerDao;
final players = playerDao.getAllPlayers();
return players;
}
}

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 can i using image_cropper i have this error?

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?