I'm trying to download a file through webview_flutter, but the file won't download.
I've already got permissions to read and write to disk, but file download is nowhere to be found.
I expected the file to be downloaded to android. Can't find anything on downloading files in webview_flutter docs. I have tried alternate packages, but their solutions are messy or deprecated.
What is the standard way to download files from WebView in Flutter?
main.dart:
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
WebViewController controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// Update loading bar.
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {}
),
)
..loadRequest(Uri.parse('https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/'));
#override
Widget build(BuildContext context) {
Permission.storage.request();
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(title: const Text('Flutter Simple Example')),
body: WebViewWidget(controller: controller),
);
}
}
Related
I am trying to share a file using SharePlus. However, I get the following error:
The task is to generate a PDF file and share it through ios and android. I see that share_plus is able to share the file. However, I am unable to share by saving it in the applicationDocumentDirectory.
Update: I have attached a demo repo with codes from below. The error is showing in my app even when the repo is working without permissions fine. share_plus complains with below issues.
Repo: Link
Error:
Unhandled Exception: PlatformException(error, Failed to find configured root that contains /data/user/0/com.example.flutter_share_demo/app_flutter/someRandom.pdf, null, java.lang.IllegalArgumentException: Failed to find configured root that contains /data/user/0/com.example.flutter_share_demo/app_flutter/someRandom.pdf
The code is as follows:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Share files')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: TextButton(
child: const Text('Generate and Share PDF'),
onPressed: () async {
final pdf = pw.Document();
pdf.addPage(pw.Page(
build: (context) =>
pw.Center(child: pw.Text('Hello, World!')),
));
final Directory storageDir = getApplicationDocumentDirectory();
try {
File file = File('${storageDir.path}/someRandom.pdf');
await file.writeAsBytes(await pdf.save());
print(file.path);
print('File exists: ${await file.exists()}');
Share.shareFiles([file.path], subject: 'Shared file');
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Permission denied')));
}
} on PlatformException catch (ex) {
print(ex);
} catch (ex) {
print(ex);
}
},
),
),
],
));
}
}
Context
I have an application in Kotlin (native Android) and it sends data to an attached module in Flutter. From Kotlin I send _numA2F, and I want to show it on flutter view, but it isn't working. The other variable (_numF2A) that I'm going to send back to the native app is getting updated properly.
Question
Could you please point out why _numA2F isn't taking the value received from the native android application? I already confirmed that the number that I send from Kotlin is received in the flutter module.
This is my code in Flutter:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _numA2F = 1;
int _numF2A = 1;
static const platform = const MethodChannel('com.jssm.af/data');
_MyHomePageState() {
platform.setMethodCallHandler(_receiveFromHost);
}
Future<void> _receiveFromHost(MethodCall call) async {
int number = 11;
try {
print('CHECK THIS OUT!!!!!!!!!');
print(call.method);
if (call.method == "fromHostToClient") {
final String data = call.arguments;
print(call.arguments);
final jData = jsonDecode(data);
number = jData['numA2F'];
}
} on PlatformException catch (e) {
print(e);
}
setState(() {
_numA2F = number;
print("_numberA2F: " + _numA2F.toString());
});
}
void _doubleNumber() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_numF2A = 2 * _numA2F;
});
}
#override
Widget build(BuildContext context) {
print('REBUILDING!!!!!!!!!!');
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Data received from fa_Android',
),
Text(
'$_numA2F',
style: Theme.of(context).textTheme.headline4,
),
Text(
'Number to be returned (double):',
),
Text(
'$_numF2A',
style: Theme.of(context).textTheme.headline4,
),
RaisedButton(
onPressed: _doubleNumber,
child: const Text('Send Result to Android',
style: TextStyle(fontSize: 20)),
)
],
),
),
);
}
}
Remove this:
_MyHomePageState() {
platform.setMethodCallHandler(_receiveFromHost);
}
And use an initState function like this:
#override
void initState() {
_receiveFromHost(call);
}
or better still use:
_MyHomePageState() {
_receiveFromHost(call);
}
I have an android SDK that integrates a Flutter module. the Dart code is the basic increment example from Flutter.
I am trying to load the Dart code into a FlutterView. I notice though a print the Dart code is called, but the widget is not displayed
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<io.flutter.embedding.android.FlutterView
android:id="#+id/flutter_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
the code that loads the dart code (in a View.OnAttachStateChangeListener):
override fun onViewAttachedToWindow(v: View?) {
v?.run {
FlutterMain.startInitialization(context)
FlutterMain.ensureInitializationComplete(context,null);
val flutterEngine = FlutterEngine(context)
flutterEngine.dartExecutor.executeDartEntrypoint(
// set which of dart methode will be used here
DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(), "myMainDartMethod")
// to set here the main methode you can use this function to do this
// inteade of DartEntrypoint(FlutterMain.findAppBundlePath(),"myMainDartMethod")
// write this mdethode DartEntrypoint.createDefault()
//DartExecutor.DartEntrypoint.createDefault()
)
flutterView = findViewById(R.id.flutter_view)
flutterView.attachToFlutterEngine(flutterEngine)
}
}
I have used "myMainDartMethod" and DartExecutor.DartEntrypoint.createDefault() both don't work
the dart code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
#pragma('vm:entry-point') // say the release that this function must alos in the project used and it must not deleted
void myMainDartMethod() => runApp(MyApp()); // I use this function to show in the android activity
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
print("Flutter/MyApp in dart is called");
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
notice the print, which is actually being called but the UI is not visible in the Android side (FlutterView).
What am I missing? What can I add/change to display the code?
the problem was I was missing lifecycleChannel state.
I have added the following line right after the instantiation of FlutterEngine
val flutterEngine = FlutterEngine(context)
flutterEngine.lifecycleChannel.appIsResumed()
of course, you will probably need to call other lifecycleChannel methods in the correct place
source: https://medium.com/#kassan424/sample-example-how-flutterview-in-a-android-activity-can-be-use-b9a887cd1d7
Is it possible to add a Flutter widget or UI element to an Android View?
I am developing an Android SDK, where I work only with views and not activities or fragments
I get the view instance in a View.OnAttachStateChangeListener :
override fun onViewAttachedToWindow(view: View) {
}
override fun onViewDetachedFromWindow(view: View) {
}
and the view layout is a simple LinearLeayout or FrameLayout
I want to add a Flutter .arr to the project and display a widget inside the view. moreover I would want all the routes and UI that comes with the widget.
example, display the basic example from Flutter in a view and not in an activity, can it be done?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in a Flutter IDE). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
I think you can't just add a Widget or any UI element from Flutter SDK into an Android View. Flutter Widgets need flutter context and flutter engine to work.
But, you can launch Flutter View into android native app https://flutter.dev/docs/development/add-to-app
I want to get all file in listview with flutter project but how to access the external folder.
I have created a folder with name 'MyFile' and it is created at "/storage/emulated/0/MyFile",
but below code pointing at "/storage/emulated/0/Android/data/com.example.demo/MyFile".
I don't know why below code is not working
Directory externalDirectory = await getExternalStorageDirectory();
print('External Storage:$externalDirectory');
// External storage: /storage/emulated/0/Android/data/com.example.demo/MyFile
When using Flutter Official path_provider package, getExternalStorageDirectory() will always return path to /storage/emulated/0/your-package-name/files.
To get /storage/emulated/0/, you can used a Third-party package ext_storage. Below code will return your desired Directory path
var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory();
print(path); // /storage/emulated/0
Now to create a Folder, you can use the below function:
//this will create a Folder in the storage/emulated/0
new Directory(externalDirectoryPath +'/YourfolderName')
.create()
.then((Directory directory)
{
print(directory.path);
});;
'
Edit post picture 2 to prove it work.
code snippet to create directory , file
new Directory('/storage/emulated/0/MyFile').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
.then((File file) {
// Stuff to do after file has been created...
print('${file.path}');
});
var dir = Directory('/storage/emulated/0/MyFile');
print('${dir.path}');
print('${dir.list().toList()}');
full code for create directory and file
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:simple_permissions/simple_permissions.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
new Directory('/storage/emulated/0/MyFile').create()
// The created directory is returned as a Future.
.then((Directory directory) {
print(directory.path);
});
new File('/storage/emulated/0/MyFile/test.txt').create(recursive: true)
.then((File file) {
// Stuff to do after file has been created...
print('${file.path}');
});
var dir = Directory('/storage/emulated/0/MyFile');
print('${dir.path}');
print('${dir.list().toList()}');
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
SimplePermissions.requestPermission(Permission.WriteExternalStorage);
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
please use package flutter_file_manager https://pub.dev/packages/flutter_file_manager
I have tested with real device, it works fine
full code
// framework
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
// packages
import 'package:flutter_file_manager/flutter_file_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:simple_permissions/simple_permissions.dart';
void main() => runApp(new MyApp());
#immutable
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
//SimplePermissions.requestPermission(Permission.ReadExternalStorage);
SimplePermissions.requestPermission(Permission.WriteExternalStorage);
return new MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter File Manager Demo"),
),
body: FutureBuilder(
future: _files(), // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Press button to start.');
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Awaiting result...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return snapshot.data != null
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) => Card(
child: ListTile(
title: Column(children: [
Text('Size: ' +
snapshot.data[index]
.statSync()
.size
.toString()),
Text('Path: ' +
snapshot.data[index].path.toString()),
Text('Date: ' +
snapshot.data[index]
.statSync()
.modified
.toUtc()
.toString())
]),
subtitle: Text(
"Extension: ${p.extension(snapshot.data[index].absolute.path).replaceFirst('.', '')}"), // getting extension
)))
: Center(
child: Text("Nothing!"),
);
}
return null; // unreachable
},
)),
);
}
_files() async {
var root = await getExternalStorageDirectory();
var files = await FileManager(root: root).walk().toList();
for(var i = 0;i<files.length;i++) {
print("${files[i].path} ");
}
return files;
}
}
working demo in emulator
I had the same problem, while Android SDK version >30 or 31 doesn't allow to read from other directories but you definitely read from your directory without any permission.
Add '//' + directory path & your problem will be resolved
So it means that your path will be '//'+ getExternalStorageDirectory())!.path
This is the code to save and retrieve the file work on both SDK > 30 and SDK =< 30.
final directory = (await getExternalStorageDirectory())!.path;
ByteData? byteData =
await (image.toByteData(format: ui.ImageByteFormat.png));
Uint8List pngBytes = byteData!.buffer.asUint8List();
File imgFile = new File('$directory/screenshot${rng.nextInt(2000)}.png');
await imgFile.writeAsBytes(pngBytes);
setState(() {
_imageFile = imgFile;
});
// Add '//' + directory path & your problem will be resolved
return '//'+imgFile.path;
First I'm saving the image in the directory then I'm reading it.