Created a function to pick file on onPressed() of Elevated Button, and pass the files to a new function openfiles() and then in open files function, I call a widget show() and pass the parameters to it. How to return in listView. The default constructor takes an explicit List of children. This constructor is appropriate for list views with a small number of children because constructing the List requires doing work for every child that could possibly be displayed in the list view instead of just those children that are actually visible.
pickFile class
return Scaffold(
body: Column(
children: [
Container(
child: ElevatedButton(
onPressed: () async {
final result =
await FilePicker.platform.pickFiles(allowMultiple:true);
if (result == null) return;
openFiles(result.files);
},
child: const Text("pick file"),
),
),
Text("data"),
],
),
);
}
void openFiles(List<PlatformFile> files) {
show(files: files);
}
}
ListView in UI
import 'package:file_picker/src/platform_file.dart';
import 'package:flutter/material.dart';
Widget show({
List<PlatformFile>? files,
}) {
return Scaffold(
body: ListView.builder(
itemCount: files!.length,
itemBuilder: (context, index) {
final file = files[index];
return buildFile(file);
}),
);}
Widget buildFile(PlatformFile file) {
final kb = file.size / 1024;
final mb = kb / 1024;
final size =
(mb >= 1) ? '${mb.toStringAsFixed(2)} MB' : '${kb.toStringAsFixed(2)} KB';
return Container(
width: 100,
height: 100,
child: InkWell(
onTap: () => null,
child: Container(
width: 200,
height: 200,
child: ListTile(
leading: (file.extension == 'jpg' || file.extension == 'png')
? Image.file(
File(file.path.toString()),
width: 80,
height: 80,
)
: Container(
width: 80,
height: 80,
),
title: Text('${file.name}'),
subtitle: Text('${file.extension}'),
trailing: Text(
'$size',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
),
),
);
}
CodePudding user response:
You must setState your widget after fetching files. return value of show
is being ignored. (method show(files: files);
is not attached to flutter's widget tree.)
CodePudding user response:
Your show()
function is returning a Widget so you have to put it somewhere in the widget tree.
So first I would get rid of your openFiles()
function, because it doesn't really have a purpose. Then initialize a List in your _pickFileState
class:
List<PlatformFile>? files,
Then you insert you widget returned by show()
into widget tree:
Column(
children: [
Container(), //your Container here
show(files: files), //here you insert your List
],
),
And lastly when you change your function in 'onPressed' method:
ElevatedButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles(allowMultiple: true);
if (result == null) return;
files = result.files; //EDIT: THIS PROBABLY CAUSED YOU AN ERROR
setState((){});
},
)
You use setState()
to rebuild your Widget.