Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In Android Studio Emulator, the pdf file is opening but when I release its .apk file and install it on my phone, pdf file does not open. I used flutter_pdfview package to load pdf file.
This is where the page is shown.
import 'package:darpandentalhome/services/api_for_report.dart';
import 'package:darpandentalhome/shared/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:google_fonts/google_fonts.dart';
class Report extends StatefulWidget {
final String url;
Report({this.url});
#override
_ReportState createState() => _ReportState();
}
class _ReportState extends State<Report> {
String path;
#override
void initState() {
// TODO: implement initState
super.initState();
ApiService(pdfURL: widget.url).loadPDF().then((value){
setState(() {
path=value;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
centerTitle: true,
title: Text(
'Report',
style: GoogleFonts.rubik(
textStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500
)
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios,color: Colors.black,),
onPressed: () {
Navigator.pop(context);
},
),
backgroundColor: Color(0xfff9f9f9),
),
backgroundColor: Color(0xfff9f9f9),
body: path != null ? Container(
child: PDFView(
filePath: path,
),
) : Loading(),
floatingActionButton: IconButton(
icon: Icon(Icons.refresh,size: 30,),
onPressed: () {
setState(() {
path = null;
ApiService(pdfURL: widget.url).loadPDF().then((value){
setState(() {
path=value;
});
});
});
},
),
);
}
}
This is for the HTTP API service for fetching pdf file from HTTP URL.
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class ApiService{
final String pdfURL;
ApiService({this.pdfURL});
Future<String> loadPDF() async {
var response = await http.get(pdfURL);
var dir = await getExternalStorageDirectory();
File file = File(dir.path + "/data.pdf");
await file.writeAsBytes(response.bodyBytes, flush: true);
return file.path;
}
}
I thought it was a permission issue of the phone then I used storage permission in AndroidManifest file then manually allowed this permission on my phone but it also didn't work.
What is the problem here?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
it's because difference between android version
if your android version is 29 use this code in your manifest
android:requestLegacyExternalStorage="true"
This problem was solved after giving internet permission to the app since the http api need to fetch data from internet.
Here are the steps to fix:
1. Add proguard-rules.pro in android/app folder file if its not already there
2. Inside of the proguard-rules.pro file put this:
-keep class com.shockwave.**
-keepclassmembers class com.shockwave.** { *; }
3.In app/build.gradle add this:
buildTypes{
release{
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
Related
I'm having a problem in flutter on vs code
I imported the audioplayers
here's my pubspec.yaml
here's my homepage where I call the audio players
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.brown,
title: Text('anghami'),
),
body: Container(
color: Colors.brown[200],
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Card(
child: ListTile(
title: Text(
"benab",
style: TextStyle(color: Colors.red),
),
//tileColor: Colors.red,
leading: Icon(Icons.music_note),
iconColor: Colors.red,
onTap: () async {
final player = AudioPlayer();
await player
.setSource(AssetSource('assets/music/music1.mp3'));
},
),
),
],
),
),
),
);
}
}
whenever i try to play the music from the phone I get this error
P.S: the vs code has no problem in loading images or using other type of assets .
i've tried using Audiocache it doesn't work especially they deleted it in the last version ^1.1.1 ,
[enter image description here][https://i.stack.imgur.com/u9kKR.png]
It seems you trying to load an asset in /assets/assets/music/ folder.
My guess is that you want to load an asset in /assets/music/ folder and it's a simple mistake.
To fix that:
// Replace the relative path of your asset below:
// assets/music/music1.mp3 -> music/music1.mp3
await player.setSource(AssetSource('music/music1.mp3'));
Just remove assets from your audio source like this:
await player.setSource(AssetSource('music/music1.mp3'));
Firstly, create a assets directory on the root of your project , then create music folder.
Try to play with
await player.setSource(AssetSource('music/music1.mp3'));
Hello guys the solutions here are useful , so the main problem that I had was in the path so after correction it loaded the asset in a normal way,
but instead of just loading the asset you want it to play obviously and that's guaranteed by using :
**final player = AudioPlayer();**
**await player.play(AssetSource('music/music1.mp3'));**
I am creating a webview app using flutter_webview_plugin. I am stack at allowing the app to launch phone call and mailto links. When I use webview_flutter I get the bottom menus and the address bar at the top does not disappear
try using the url launcher package
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
const String _url = 'mailto:example#example.com';
void main() => runApp(
const MaterialApp(
home: Material(
child: Center(
child: ElevatedButton(
onPressed: _launchURL,
child: Text('Show Flutter homepage'),
),
),
),
),
);
void _launchURL() async {
if (!await launch(_url)) throw 'Could not launch $_url';
}
I have managed to come up with this simple solution, just add these few lines of code in your initState, you can add 'mailto:' and 'sms' if necessary.
final flutterWebviewPlugin = new FlutterWebviewPlugin();
flutterWebviewPlugin.onUrlChanged.listen((String url) {
if (url.contains("tel:")) launch(url);
});
The sdk that I use is as follows.
sdk: ">=2.7.0 <3.0.0"
image_picker: ^0.6.7
image_picker_for_web: ^0.1.0
firebase_storage: ^3.1.6
cloud_firestore: ^0.13.7
When uploading an image to storage, I try to reduce the size of the image file.
And this is the code for image upload.
import 'package:image_picker/image_picker.dart';
import 'package:firebase/firebase.dart' as fb;
import 'package:omd_test/widget/custom_loading.dart';
class TestScreen extends StatefulWidget {
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
PickedFile _image;
String imageUrl;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Scaffold(
appBar: AppBar(
title: Text("TEST"),
),
body: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
children: [
Container(
width: 200,
height: 200,
child: _image == null
? Container()
: Image.network(
_image.path,
)),
TextButton(
onPressed: () {
_getImagesPicker();
},
child: Text(
"Pick",
style: TextStyle(color: Colors.black),
)),
SizedBox(
height: 20,
),
TextButton(
onPressed: () async {
if (_image != null) {
await imageUpload(_image);
setState(() {
_image = null;
});
} else
print("No Image");
},
child: Text(
"Upload"
)),
],
),
),
),
),
);
}
Future<void> _getImagesPicker() async {
try {
final _imagePath = await ImagePicker().getImage(
source: ImageSource.gallery,
imageQuality: 10,
maxHeight: 50,
maxWidth: 50
);
setState(() {
_image = _imagePath;
});
} catch (err) {
print(err);
}
}
Future<String> imageUpload(PickedFile image) async {
var bytes = await image.readAsBytes();
fb.StorageReference _storage =
fb.storage().ref('testScreen/${image.path}.jpg');
fb.UploadTaskSnapshot uploadTaskSnapshot = await _storage
.put(bytes, fb.UploadMetadata(contentType: 'image/png'))
.future;
var imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
imageUrl = imageUri.toString();
return imageUrl;
}
}
I tested by changing the value of 'imageQuality' of ImagePicker, but when uploaded to storage, all image files were the same size.
enter image description here
Can I know what the problem is?
Is it a problem to upload to storage?
Thank you.
From the image_picker repository, there's some inconsistency in what adjustments can be made to what type of images.
Here's an overview that might give some important lead.
Can I know what the problem is?
The comments in the actual implementation of the package has some lines[here]:
//Note that the `maxWidth`, `maxHeight` and `imageQuality` arguments are not supported on the web. If any of these arguments is supplied, it'll be silently ignored by the web version of the plugin.
However, there's still an implementation of the resizing of a selected image though.
Is it a problem to upload to storage?
Seemingly no.
Here's what you may wish to try going forward; run your app on other platforms and try to establish if the image is resized, this will help you single out if it's only on the web that the quality is not being adjusted.
If you establish this to be so, you may wish to have your own implementation of quality/size adjustment of the picked media, you can utilise kIsWeb boolean property to determine if it's web, then apply your own implementation.
if(kIsWeb){
//Adjust quality/size
}else{
//use the already adjusted media
}
Note this comment as well:
//Compression is only supported for certain image types such as JPEG and on Android PNG and WebP, too. If compression is not supported for the image that is picked, a warning message will be logged.
I am using flutter_webview_plugin: ^0.3.8 but I have the same problem with webview_flutter: ^0.3.13.
In webview, I want to make use of a website which triggers a file download on successful completion of a captcha. However, I complete the captcha and nothing happens, no download.
Is there something in Flutter like a webview download listener ("webview.setDownloadListener")? I only need this for Android.
If not, is there a way of downloading files from a webview in Flutter?
A similar issue can be found here!
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews. It can recognize downloadable files in both Android (using setDownloadListener) and iOS platforms!
I report here the same answer that I gave to the similar issue:
To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!
Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then, you need to ask permission using the permission_handler plugin. Instead, to effectively download your file, you can use the flutter_downloader plugin.
Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(
debug: true // optional: set false to disable printing logs to console
);
await Permission.storage.request();
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController webView;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialUrl: "http://ovh.net/files/1Mio.dat",
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
useOnDownloadStart: true
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) {
},
onDownloadStart: (controller, url) async {
print("onDownloadStart $url");
final taskId = await FlutterDownloader.enqueue(
url: url,
savedDir: (await getExternalStorageDirectory()).path,
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
},
))
])),
),
);
}
}
Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.
just add this code to your AndroidManifest.xml
<provider
android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
android:authorities="${applicationId}.flutter_downloader.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
and add this code to your AndroidManifest.xml
it works to me
it works for me
require plugin https://pub.dev/packages/url_launcher
add this code to your project to download file from flutter webview
onDownloadStart: (controller, url,) async {
// print("onDownloadStart $url");
final String _url_files = "$url";
void _launchURL_files() async =>
await canLaunch(_url_files) ? await launch(_url_files) : throw 'Could not launch $_url_files';
_launchURL_files();
},
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I can overlay images using the Stack Widget in Flutter, but how to convert that overlayed widgets to a real image in png or jpeg format that users can save on their phone?
Context: I want to make a logo maker app, I have image assets in my project, the user may combine these assets to make a logo.
You can use RepaintBoundary for that.
Check this link,
regarding saving image to disk, you need to process the bytes taken, you can use the image package (made mostly for dart, but 100% compatible with flutter).
As you see, the code is very simple once you convert the bytes between Flutter Image and image:image
new File('thumbnail.png').writeAsBytesSync(encodePng(convertedBytes));
You can check this prototype code I made yesterday for a similar question regarding reading image pixels in Flutter.
Once you've got the Image bytes, you can stream it to a file in disk (using path_provider or similar to find the File's path in each OS), or upload it somewhere, like the first article.
Good luck with the implementation!
Try the following code it takes the screenshot of the screen and save the file in the internal storage.
pubspec.yaml
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
# package for saving the screenshot
image_picker_saver: ^0.1.0
main.dart
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:image_picker_saver/image_picker_saver.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static GlobalKey screenshotKey = new GlobalKey(); // key
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: RepaintBoundary(
key: screenshotKey,
child: Container(
width: double.infinity,
color: Colors.white,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
RaisedButton(
child: Text("Take a screenshot"),
onPressed: _takeScreenShot,
)
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _takeScreenShot() async {
RenderRepaintBoundary boundary =
screenshotKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
var filePath = await ImagePickerSaver.saveFile(fileData: pngBytes);
print(filePath);
}
}