Flutter: How do I select and display images - image

I cannot display selected images from gallery in a grid. In this code, I am displaying images in a list and I want to turn it into small grid type in 1 row but I don't know how. Can you please help?
Here's my code for selecting multiple images using file picker.
FileType fileType;
String imgName, _imgPath;
Map<String, String> imgPaths;
List<File> _imgList = List();
bool isLoadingPath = false;
_openFile() async {
setState(() => isLoadingPath = true);
try {
_imgPath = null;
imgPaths = await FilePicker.getMultiFilePath(
type: fileType != null ? fileType : FileType.custom,
allowedExtensions: ['jpg', 'png']);
_imgList.clear();
imgPaths.forEach((key, val) {
print('{ key: $key, value: $val}');
File file = File(val);
_imgList.add(file);
});
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
setState(() {
isLoadingPath = false;
imgName = _imgPath != null
? _imgPath.split('/').last
: imgPaths != null
? imgPaths.keys.toString()
: '...';
});
}
Displaying images in a list. (How to display images as it is?)
Widget _fileBuilder() {
return Builder(
builder: (BuildContext context) => isLoadingPath
? Padding(
padding: const EdgeInsets.only(bottom: 4.0))
: _imgPath != null || imgPaths != null && (imgPaths.length > 1 && imgPaths.length < 5)
? new Container(
height: imgPaths.length > 1
? MediaQuery.of(context).size.height * 0.15
: MediaQuery.of(context).size.height * 0.10,
width: MediaQuery.of(context).size.width,
child: new Scrollbar(
child: new ListView.separated(
itemCount: imgPaths != null && imgPaths.isNotEmpty
? imgPaths.length
: 1,
itemBuilder: (BuildContext context, int index) {
final bool isMultiPath = imgPaths != null && imgPaths.isNotEmpty;
final int fileNo = index + 1;
final String name = 'File $fileNo : ' + (isMultiPath
? imgPaths.keys.toList()[index]
: _imgPath ?? '...');
final filePath = isMultiPath
? imgPaths.values.toList()[index].toString()
: _imgPath;
return new ListTile(
title: Transform.translate(
offset: Offset(-25, 0),
child: new Text(
name,
),
),
leading: Icon(Icons.attach_file_outlined, color: Color(0xFFF3A494),),
dense: true,
);
},
separatorBuilder:
(BuildContext context, int index) =>
new Divider(),
)),
)
: new Container(child: Text('4 photos is the maximum'),),
);
}
Dependencies:
file_picker: ^1.4.2
path:
mime:
async:

what you can do is, use the Image Picker dependency. You can find its documentation on pub.dev. after installing it, try using it and store the image uploaded in a file in the device. and with that file name, you can access the image.
You can try the below code, it worked for me. Also don't forget to import dart:io; for using file.
var _storedImage;
Future<void> _takePictureByCamera() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.camera, maxWidth: 600, imageQuality: 60);
setState(() {
_storedImage = File(imageFile!.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile!.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Future<void> _takePictureByGallery() async {
final picker = ImagePicker();
final imageFile =
await picker.getImage(source: ImageSource.gallery, maxWidth: 600);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = File(imageFile.path);
});
final appDir = await path_provider.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = File(imageFile.path).copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
and after selecting or clicking the image, you can do this to display the image ->
void getImage() async {
final pickedImage = await showModalBottomSheet(
context: accountTabScaffoldMessengerKey.currentContext!,
backgroundColor: Colors.transparent,
enableDrag: true,
// elevation: 0,
builder: (context) => AccountImageUpdateBottomSheet(_selectImage),
);
_selectImage(pickedImage);
}
void _selectImage(File pickedImage) {
setState(() {
_pickedImage = pickedImage;
});
}
The image you selected is stored in the _pickedImage and you can access it by Image.file(_pickedImage).

Related

flutter visibility error and initState problem

i'm a beginner and i have a strange errori got a problem in visibility i work with laravel api if i have no products in database this.widget.client always false , if i have a product in database the application works perfectly !!
flutter code :
bool client=false ;
_getAuthenticatedUser() async {
SharedPreferences _prefs = await SharedPreferences.getInstance();
var log = new Logger();
var x = _prefs.getString('photoUser');
this.widget.photo=json.decode(x);
this.widget.name= json.decode(_prefs.getString('Username'));
if(_prefs.getString('token')!=null){
if(json.decode(_prefs.getString('role'))=='superAdmin'){
this.widget.superAdmin=true;}else{this.widget.superAdmin=false;}
if(json.decode(_prefs.getString('role'))=='admin'){
this.widget.admin=true;
}else{this.widget.admin=false;}
if(json.decode(_prefs.getString('role'))=='user'){
_prefs.setString('client', 'client');
this.widget.client=true;
}else{this.widget.client=false; log.d('here not client');}
}
else{
this.widget.superAdmin=false;
this.widget.admin=false;
this.widget.client=false;
}
}
_getAllProducts() async {
var _productService = ProductService();
var products = await _productService.getProducts();
var result = json.decode(products.body);
var log = new Logger();
_productList.clear();
result.forEach((data) {
var product = Product();
product.id = data['id'] ?? 0 ;
product.name = data['name'] ?? "";
product.photo = data['photo'] ?? "";
product.price = data['price'] ?? 0;
product.discount = data['discount'] ?? 0;
product.detail = data['detail'] ?? 'No detail';
product.quantity = data['quantity'] ?? 0;
setState(() {
_productList.add(product);
});
});
}
#override
void initState(){
super.initState();
_getAuthenticatedUser();
_getAllProducts();}
and in the build
Visibility(
visible: this.widget.client,
child: ListTile(
leading: Icon(Icons.category,color: Colors.white,),
title: Text('Produits refusé',style: TextStyle(color: Colors.white)),
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) =>RefusedProducts(_refusedProductList,this.widget.client,this.widget.photo,this.widget.name)));
}
),),
You can wrap your setState() function like this:
WidgetsBinding.instance?.addPostFrameCallback((_) {
setState(() {
_productList.add(product);
});
});

Convert Uint8List image data to ImageGallerySaver saveFile String

how can I convert the Uint8List imagedata of the Screenshot Package to save it with the ImageGallerySaver package saveFile command, which needs a string?
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result = await ImageGallerySaver.saveFile();
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
I found a solution:
TextButton(
onPressed: () {
_imageFile = null;
screenshotController
.capture()
.then((Uint8List image) async {
//print("Capture Done");
String dir =
(await getApplicationDocumentsDirectory()).path;
File file = File("$dir/" +
DateTime.now().millisecondsSinceEpoch.toString() +
".png");
await file.writeAsBytes(image);
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveFile(file.path);
print("File Saved to Gallery");
}).catchError((onError) {
print(onError);
});
},
child: Icon(Icons.change_history),
), // Thi

Cast Future<File> to base64 image with Flutter

Hi the flutter code below loads a photo from the camera roll and then displays it, on video, what I have to do is recover the path of the file, to do it I use the code below inside the inserimento function but when I run the code I the following error:
Try correcting the name to the name of an existing getter, or defining
a getter or field named 'path'. print("\n Immagine:
"+imageFile.path);
Flutter Code:
Future<File> imageFile;
//Costruttore
ArticoloEditPage(){
aggiornaValori();
BackButtonInterceptor.add(myInterceptor);
setData(new DateTime.now());
}
//Disabilito il bottone di back su android
bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
return true;
}
//Funzione di init
void init() {
aggiornaValori();
BackButtonInterceptor.add(myInterceptor);
}
//Funzione che esegue la creazione dell'utente
Future<bool> inserimento(BuildContext context) async {
print("\n Immagine: "+imageFile.path);
// var base64File=await Supporto.castDocumentToBase64(imgPath);
//print("\n Immagine in base64: "+imgPath);
}
pickImageFromGallery(ImageSource source) {
setState(() {
imageFile = ImagePicker.pickImage(source: source);
});
}
Widget showImage() {
return FutureBuilder<File>(
future: imageFile,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.data != null) {
return Image.file(
snapshot.data,
width: 300,
height: 300,
);
} else if (snapshot.error != null) {
return const Text(
'Errore caricamento non riuscito',
textAlign: TextAlign.center,
);
} else {
return const Text(
'Nessuna immagine selezionata',
textAlign: TextAlign.center,
);
}
},
);
}
you can not get path directly in future method,
so
by
1. this you can print your path.
Future<bool> inserimento(BuildContext context) async {
var pathData=await imageFile;
print("\n Immagine: "+pathData.path);
}
or
2. if you need path in widget
Widget showImage() {
return FutureBuilder<File>(
future: imageFile,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.data != null) {
print("Your Path : "+snapshot.data.path);
return Image.file(
snapshot.data,
width: 300,
height: 300,
);
} else if (snapshot.error != null) {
return const Text(
'Errore caricamento non riuscito',
textAlign: TextAlign.center,
);
} else {
return const Text(
'Nessuna immagine selezionata',
textAlign: TextAlign.center,
);
}
},
);
}
also
3. if you need base64 image.
then
Future<bool> inserimento(BuildContext context) async {
var pathData=await imageFile;
var base64Image = base64Encode(pathData.readAsBytesSync());
print("\n Immagine base64Image: "+base64Image.toString());
}

how to set a picked image in flutter

I tried using this for picking and Saving Image->
File imageFile;
Future getImage(int type) async {
PickedFile pickedImage = await ImagePicker().getImage(
source: type == 1 ? ImageSource.camera :
ImageSource.gallery,
imageQuality: 50
);
if (pickedImage == null) return;
File tmpFile = File(pickedImage.path);
tmpFile = await tmpFile.copy(tmpFile.path);
setState(() {
imageFile = tmpFile;
});
}
imageFile != null
? Image.file(
imageFile,
height: MediaQuery.of(context).size.height / 5,
)
: Text("Pick up the image"),
But, Image is not saving. Nothing has been Displayed. What else I need to do?
This code is very ambiguous, it's very unclear where you are calling getImage and where you are setting the image.
I suppose you are not calling getImage() properly and not sure where you are using this if (pickedImage == null) return; it might be wrong.
Anyway, here's a proper explanation it should work.
Declare your getImage method inside the Widget class.
Future<File> getImage(int type) async {
PickedFile pickedImage = await ImagePicker().getImage(
source: type == 1 ? ImageSource.camera :
ImageSource.gallery,
imageQuality: 50
);
return pickedImage;
}
Declare the File state variable in the sate class
File imageFile;
Have a Button for the selecting action of the image in your widget.
...
IconButton(
icon: Icon(Icons.gallery),
onPressed: () {}
)
...
call the getImage method and setState the result in the onPressed handler.
...
IconButton(
icon: Icon(Icons.gallery),
onPressed: () async {
final tmpFile = await getImage(1);
setState(() {
imageFile = tmpFile;
});
)
...
Display your file in a widget
imageFile != null
?Image.file(
imageFile,
height: MediaQuery.of(context).size.height / 5,
): Text("Pick up the image"),

Flutter: Is there any way to get "fix size"/"reduce size" of DataColumn in "DataTable"?

Is there is any way to reduce the size of DataColumn?
I am Using DataTable Class in Flutter
columns: <DataColumn> [
DataColumn(
label: Text("Column A",
style: Theme.of(context).textTheme.subtitle),
numeric: false,
onSort: (i, b) {},
tooltip: "Perticulars",
),
DataColumn(
label: Text("Column B",
style: Theme.of(context).textTheme.subtitle),
numeric: false,
onSort: (i, b) {},
tooltip: "As per Assessee",
),
DataColumn(
label:
Text("Column C", style: Theme.of(context).textTheme.subtitle),
numeric: false,
onSort: (i, b) {},
tooltip: "As per ITD",
)
],
I removed some code about sort. You can change _tablePadding and _columnSpacing to reduce the size:
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class CustomDataTable extends DataTable {
CustomDataTable({
Key key,
#required this.columns,
this.sortColumnIndex,
this.sortAscending = true,
this.onSelectAll,
#required this.rows,
}) :
assert(columns != null),
assert(columns.isNotEmpty),
assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)),
assert(sortAscending != null),
assert(rows != null),
assert(!rows.any((DataRow row) => row.cells.length != columns.length)),
_onlyTextColumn = _initOnlyTextColumn(columns),
super(
key: key,
columns: columns,
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: onSelectAll,
rows: rows);
final List<DataColumn> columns;
final int sortColumnIndex;
final bool sortAscending;
final ValueSetter<bool> onSelectAll;
final List<DataRow> rows;
static const double _headingRowHeight = 56.0;
static const double _dataRowHeight = 48.0;
static const double _tablePadding = 18.0;
static const double _columnSpacing = 56.0;
static const double _headingFontSize = 12.0;
static const Duration _sortArrowAnimationDuration = Duration(milliseconds: 150);
static const Color _grey100Opacity = Color(0x0A000000); // Grey 100 as opacity instead of solid color
static const Color _grey300Opacity = Color(0x1E000000); // Dark theme variant is just a guess.
final int _onlyTextColumn;
static int _initOnlyTextColumn(List<DataColumn> columns) {
int result;
for (int index = 0; index < columns.length; index += 1) {
final DataColumn column = columns[index];
if (!column.numeric) {
if (result != null)
return null;
result = index;
}
}
return result;
}
bool get _debugInteractive {
return columns.any((DataColumn column) => false)
|| rows.any((DataRow row) => false);
}
static final LocalKey _headingRowKey = UniqueKey();
void _handleSelectAll(bool checked) {
if (onSelectAll != null) {
onSelectAll(checked);
} else {
for (DataRow row in rows) {
if ((row.onSelectChanged != null) && (row.selected != checked))
row.onSelectChanged(checked);
}
}
}
Widget _buildCheckbox({
Color color,
bool checked,
VoidCallback onRowTap,
ValueChanged<bool> onCheckboxChanged,
}) {
Widget contents = Semantics(
container: true,
child: Padding(
padding: const EdgeInsetsDirectional.only(start: _tablePadding, end: _tablePadding / 2.0),
child: Center(
child: Checkbox(
activeColor: color,
value: checked,
onChanged: onCheckboxChanged,
),
),
),
);
if (onRowTap != null) {
contents = TableRowInkWell(
onTap: onRowTap,
child: contents,
);
}
return TableCell(
verticalAlignment: TableCellVerticalAlignment.fill,
child: contents,
);
}
Widget _buildHeadingCell({
BuildContext context,
EdgeInsetsGeometry padding,
Widget label,
String tooltip,
bool numeric,
VoidCallback onSort,
bool sorted,
bool ascending,
}) {
label = Container(
padding: padding,
height: _headingRowHeight,
alignment: numeric ? Alignment.centerRight : AlignmentDirectional.centerStart,
child: AnimatedDefaultTextStyle(
style: TextStyle(
// TODO(ianh): font family should match Theme; see https://github.com/flutter/flutter/issues/3116
fontWeight: FontWeight.w500,
fontSize: _headingFontSize,
height: math.min(1.0, _headingRowHeight / _headingFontSize),
color: (Theme.of(context).brightness == Brightness.light)
? ((onSort != null && sorted) ? Colors.black87 : Colors.black54)
: ((onSort != null && sorted) ? Colors.white : Colors.white70),
),
softWrap: false,
duration: _sortArrowAnimationDuration,
child: label,
),
);
if (tooltip != null) {
label = Tooltip(
message: tooltip,
child: label,
);
}
if (onSort != null) {
label = InkWell(
onTap: onSort,
child: label,
);
}
return label;
}
Widget _buildDataCell({
BuildContext context,
EdgeInsetsGeometry padding,
Widget label,
bool numeric,
bool placeholder,
bool showEditIcon,
VoidCallback onTap,
VoidCallback onSelectChanged,
}) {
final bool isLightTheme = Theme.of(context).brightness == Brightness.light;
if (showEditIcon) {
const Widget icon = Icon(Icons.edit, size: 18.0);
label = Expanded(child: label);
label = Row(
textDirection: numeric ? TextDirection.rtl : null,
children: <Widget>[ label, icon ],
);
}
label = Container(
padding: padding,
height: _dataRowHeight,
alignment: numeric ? Alignment.centerRight : AlignmentDirectional.centerStart,
child: DefaultTextStyle(
style: TextStyle(
// TODO(ianh): font family should be Roboto; see https://github.com/flutter/flutter/issues/3116
fontSize: 13.0,
color: isLightTheme
? (placeholder ? Colors.black38 : Colors.black87)
: (placeholder ? Colors.white30 : Colors.white70),
),
child: IconTheme.merge(
data: IconThemeData(
color: isLightTheme ? Colors.black54 : Colors.white70,
),
child: DropdownButtonHideUnderline(child: label),
),
),
);
if (onTap != null) {
label = InkWell(
onTap: onTap,
child: label,
);
} else if (onSelectChanged != null) {
label = TableRowInkWell(
onTap: onSelectChanged,
child: label,
);
}
return label;
}
#override
Widget build(BuildContext context) {
assert(!_debugInteractive || debugCheckHasMaterial(context));
final ThemeData theme = Theme.of(context);
final BoxDecoration _kSelectedDecoration = BoxDecoration(
border: Border(bottom: Divider.createBorderSide(context, width: 1.0)),
// The backgroundColor has to be transparent so you can see the ink on the material
color: (Theme.of(context).brightness == Brightness.light) ? _grey100Opacity : _grey300Opacity,
);
final BoxDecoration _kUnselectedDecoration = BoxDecoration(
border: Border(bottom: Divider.createBorderSide(context, width: 1.0)),
);
final bool showCheckboxColumn = rows.any((DataRow row) => row.onSelectChanged != null);
final bool allChecked = showCheckboxColumn && !rows.any((DataRow row) => row.onSelectChanged != null && !row.selected);
final List<TableColumnWidth> tableColumns = List<TableColumnWidth>(columns.length + (showCheckboxColumn ? 1 : 0));
final List<TableRow> tableRows = List<TableRow>.generate(
rows.length + 1, // the +1 is for the header row
(int index) {
return TableRow(
key: index == 0 ? _headingRowKey : rows[index - 1].key,
decoration: index > 0 && rows[index - 1].selected ? _kSelectedDecoration
: _kUnselectedDecoration,
children: List<Widget>(tableColumns.length),
);
},
);
int rowIndex;
int displayColumnIndex = 0;
if (showCheckboxColumn) {
tableColumns[0] = const FixedColumnWidth(_tablePadding + Checkbox.width + _tablePadding / 2.0);
tableRows[0].children[0] = _buildCheckbox(
color: theme.accentColor,
checked: allChecked,
onCheckboxChanged: _handleSelectAll,
);
rowIndex = 1;
for (DataRow row in rows) {
tableRows[rowIndex].children[0] = _buildCheckbox(
color: theme.accentColor,
checked: row.selected,
onRowTap: () => row.onSelectChanged != null ? row.onSelectChanged(!row.selected) : null ,
onCheckboxChanged: row.onSelectChanged,
);
rowIndex += 1;
}
displayColumnIndex += 1;
}
for (int dataColumnIndex = 0; dataColumnIndex < columns.length; dataColumnIndex += 1) {
final DataColumn column = columns[dataColumnIndex];
final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
start: dataColumnIndex == 0 ? showCheckboxColumn ? _tablePadding / 2.0 : _tablePadding : _columnSpacing / 2.0,
end: dataColumnIndex == columns.length - 1 ? _tablePadding : _columnSpacing / 2.0,
);
if (dataColumnIndex == _onlyTextColumn) {
tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(flex: 1.0);
} else {
tableColumns[displayColumnIndex] = const IntrinsicColumnWidth();
}
tableRows[0].children[displayColumnIndex] = _buildHeadingCell(
context: context,
padding: padding,
label: column.label,
tooltip: column.tooltip,
numeric: column.numeric,
onSort: () => column.onSort != null ? column.onSort(dataColumnIndex, sortColumnIndex == dataColumnIndex ? !sortAscending : true) : null,
sorted: dataColumnIndex == sortColumnIndex,
ascending: sortAscending,
);
rowIndex = 1;
for (DataRow row in rows) {
final DataCell cell = row.cells[dataColumnIndex];
tableRows[rowIndex].children[displayColumnIndex] = _buildDataCell(
context: context,
padding: padding,
label: cell.child,
numeric: column.numeric,
placeholder: cell.placeholder,
showEditIcon: cell.showEditIcon,
onTap: cell.onTap,
onSelectChanged: () => row.onSelectChanged != null ? row.onSelectChanged(!row.selected) : null,
);
rowIndex += 1;
}
displayColumnIndex += 1;
}
return Table(
columnWidths: tableColumns.asMap(),
children: tableRows,
);
}
}

Resources