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);
}
},
),
),
],
));
}
}
Related
I have connected my firebase project successfully because it was running and then I added other screens and changed navigation to namedRoute and now my app won't run I have received this error: "ChromeProxyService: Failed to evaluate expression 'callback': InternalError: No frame with index 14." please help
Below is my Source Code:
My main.dart file
import 'dart:ui';
import 'package:essentials/constants.dart';
// import 'package:essentials/firebase_options.dart';
import 'package:essentials/routes.dart';
import 'package:essentials/screens/splash/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'screens/forgot_password/forgot_password_screen.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
// options: DefaultFirebaseOptions.currentPlatform,
);
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(
debugShowCheckedModeBanner: false,
title: 'Essentials_App',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
fontFamily: "muli",
textTheme: const TextTheme(
bodyText1: TextStyle(color: kTextColor),
bodyText2: TextStyle(color: kTextColor),
),
visualDensity: VisualDensity.adaptivePlatformDensity,
primarySwatch: Colors.blue,
),
// home: SplashScreen(),
initialRoute: SplashScreen.routeName,
routes: routes,
);
}
}
Then my routes.dart and this is where i want to access my routes
import 'package:essentials/screens/signin/signin_screen.dart';
import 'package:flutter/widgets.dart';
import 'package:essentials/screens/forgot_password/forgot_password_screen.dart';
import 'package:essentials/screens/home/home_screen.dart';
import 'package:essentials/screens/login_success/login_success_screen.dart';
import 'package:essentials/screens/splash/splash_screen.dart';
import 'package:essentials/screens/signup/sign_up_screen.dart';
// All our routes will be accessed here
final Map<String, WidgetBuilder> routes = {
SplashScreen.routeName: (context) => SplashScreen(),
SignInScreen.routeName: (context) => SignInScreen(),
ForgotPasswordScreen.routeName: (context) => ForgotPasswordScreen(),
LoginSuccessScreen.routeName: (context) => LoginSuccessScreen(),
SignUpScreen.routeName: (context) => SignUpScreen(),
HomeScreen.routeName: (context) => HomeScreen(),
};
My main. dart file is where I have initialized firebase and it is where the debug is paused and it points to the initialization line of code
I tried researching about the error I found that someone had asked before and he was not answered follow this link to see his question: ChromeProxyService: Failed to evaluate expression 'FireBase.initializeApp': InternalError: No frame with index 39
can you try initialize in this way and run in web ?
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "***", // Your apiKey
appId: "***", // Your appId
messagingSenderId: "***", // Your messagingSenderId
projectId: "***", //
storageBucket: "***", // Your projectId
),
);
If you are running it in emulator may be change the emulator.
Firstly, I was trying to import a project that contains a complete Webview and I was surprised that even after running flutter clean ; flutter pub get I would still get errors.
I then tried to recreate the demo app following https://flutter.dev/docs/get-started/codelab which was working fine at first yesterday. From here I saw that I get the same errors,
Here's my .dart code for the demo app :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Sorry for showing the errors by a screenshot but the logs when building are way too long to share, since I think it's a common problem it shouldn't be that troublesome, let me know if you need the errors so I'll do a pastebin.
Thank you guys
It looks like you maybe getting some errors while getting the dependencies and flutter is not being downloaded correctly.
If its still happening review your dependencies and do a:
flutter clean
flutter pub upgrade
If it still happens, review the log of flutter pub get to see what error you maybe getting from the dependencies.
There is another command that could work if your case is that the dependencies are not being updated locally, not on your project, but on your flutter cache. You can use:
flutter pub cache repair
The only solution I found was to delete the Flutter SDK (just delete the folder you downloaded) and to reinstall via git just because I prefer it that way.
I also moved the SDK from C:/Users/my_user/ to C:/src.
Im trying to create a flutter app with a simple raised button that does the following:
sends an sms in the background using the sms package opens a webpage
2. in the app(only for 5 seconds) using url_launcher opens the phones
3. native app for making a voice call with the onPressed property.
And I wanted it to be in this order so that I can make the phone call at the end. However, the inside the onPressed opens the native phone call app first, which doesnt let my web page open unless I exit out of the phone call app.
Im having a hard time understanding why the phone call native app is opened first, even though I make the call the _makePhoneCall() method only after I make the _launchInApp(toLaunch) call. sendSMS() is being called correctly
How can I set this in a way that the phone call native app is called only after the webpage is opened in the app and follows the order? Any help would be great
Below is the piece of code:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:sms/sms.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Packages testing',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Packages testing'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _phone = '';
_launchInApp(String url) async {
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
headers: <String, String>{'my_header_key': 'my_header_value'},
);
} else {
throw 'Could not launch $url';
}
}
_makePhoneCall(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
void sendSMS() {
SmsSender sender = new SmsSender();
sender.sendSms(new SmsMessage(_phone, 'Testing Handset'));
}
#override
Widget build(BuildContext context) {
const String toLaunch = 'https://flutter.dev/';
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
onChanged: (String text) => _phone = text,
decoration:
const InputDecoration(hintText: 'Phone Number')),
),
FlatButton(
onPressed: () => setState(() {
sendSMS();
_launchInApp(toLaunch);
_makePhoneCall('tel:$_phone');
}),
child: const Text('Run All'),
),
const Padding(padding: EdgeInsets.all(16.0)),
],
),
],
),
);
}
}
You will have to use the await keyword before the _launchInApp function to make it work properly. Try the following code.
FlatButton(
onPressed: () aync {
sendSMS();
await _launchInApp(toLaunch);
_makePhoneCall('tel:$_phone');
}),
child: const Text('Run All'),
),
You created async functions but when you called them you did not specify that you want to wait for them to complete. Add the await keyword in OnPressed
This question already has answers here:
How to take a screenshot of the current widget - Flutter
(4 answers)
Closed 2 years ago.
How can I implement the in-app screenshot functionality in flutter android?
I need this function to take a screenshot of the app screen and share the picture.
are there any plugins?
I have shared an example of code where I have used Screenshot plugin available on pub.dev along with permission handler and path provider plugin. Basically this plugin wraps your widgets inside RenderRepaintBoundary and creates an screenshot of your widget.
main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screenshot/screenshot.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Screenshot Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
File _imageFile;
//Create an instance of ScreenshotController
ScreenshotController screenshotController = ScreenshotController();
#override
void initState() {
// TODO: implement initState
super.initState();
_requestPermission();
}
_requestPermission() async {
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
].request();
final info = statuses[Permission.storage].toString();
print(info);
}
void _incrementCounter() {
setState(() {
_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: Container(
child: new Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Screenshot(
controller: screenshotController,
child: Column(
children: <Widget>[
Text(
'You have pushed the button this many times:' +
_counter.toString(),
),
FlutterLogo(),
],
),
),
_imageFile != null ? Image.file(_imageFile) : Container(),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_incrementCounter();
_imageFile = null;
screenshotController
.capture(delay: Duration(milliseconds: 10))
.then((File image) async {
//print("Capture Done");
setState(() {
_imageFile = image;
});
final result =
await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery $result");
}).catchError((onError) {
print("Error: $onError");
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
_saved(File image) async {
final result = await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery");
}
}
Packages used:
screenshot:
image_gallery_saver: ^1.1.0
permission_handler:
path_provider: ^1.6.24
You will need to specify storage permissions in AndroidManifest file as below:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
To take screenshots within flutter app of the current use this screenshot package it also has example and documentation for saving the image to a folder and as well as to gallery which can also be google photos using 2 other plugins which you can find there only. I have used this plugin and it works really well if you havep any queries then you can comment below. Hope this helps you out!
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.