I am new to Flutter ,I am unable to read picked files everytime i restart my flutter app they're gone For example if i pick an image or a pdf file and show in listview its fine.But when i restart app they're gone how to fix this ? Thanks
In short please refer me how to keep files in my flutter app. Here is a short sample from my code
Widget show({
required List<PlatformFile> files,
}) {
return ListView.builder(
itemCount: files.length,
itemBuilder: (context, index) {
final file = files[index];
return buildFile(file, context);
},
);
}
Widget buildFile(PlatformFile file, BuildContext context) {
return Container(
color: Colors.white,
child: InkWell(
onTap: () {
print("File Path is ${file.path}");
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return OpenImage(pathPDF: file.path!);
//open viewPDF page on click
}));
},
child: Container(
height: 100,
width: 150,
color: Colors.white,
child: ListTile(
leading: (file.extension == 'jpg' ||
file.extension == 'jpeg' ||
file.extension == 'png')
? Image.file(
File(file.path.toString()),
fit: BoxFit.cover,
)
: Container(
width: 100,
height: 100,
),
title: Text(
'${file.name.substring(0, idx).trim()}',
style: TextStyle(
fontFamily: GoogleFonts.lato().fontFamily,
),
),
],
),
),
),
),
);
}
CodePudding user response:
To save and retrieve data from the device you can use Shared Preferences.
You are saving the path of the first file correctly when picking the file, although you are missing the await
on prefs.setString("gotPath", file!.path.toString());
.
Future<void> readPath() async {
final preferences = await SharedPreferences.getInstance();
final path = preferences.getString('gotPath');
}
In this way you can retrieve the path you saved to the device. Be careful as this function is asynchronous and thus you can use a future builder to wait on it.
Since you need to save the whole list of files to the device I am including an example on how you can do so by using getStringList
and setStringList
:
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final Future<void> _loadFileFuture = _loadFiles();
Future<void> _loadFiles() async {
final _prefs = await SharedPreferences.getInstance();
final _files = _prefs.getStringList('files');
}
Future<void> _saveFiles() async {
final _prefs = await SharedPreferences.getInstance();
final _retrievedFiles =
await _prefs.setStringList('files', _files);
_files.addAll(_retrievedFiles);
}
final List<String> _files = [];
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _loadFileFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator();
}
return ListView.builder();
});
}
}