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'));**
Related
Listen my problem in this short video.
I've tested this case by using some other audio packages(tts、text to speech), but the result is the same, is this problem caused by the Android studio emulator?
I've tried reinstalling, changing every device and API, and changing the audio buffer size,but nothing solves the problem in android studio emulator noise.
In addition, I changed the emulator to bluestacks 5 and genymotion, but it became no sound
question
1.How can I fix android studio emulator noise problem in windows 10?
2.Why can't bluestacks 5 and genymotion play sound
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key? key}) : super(key: key);
final FlutterTts flutterTts = FlutterTts();
speak() async{
//print(await flutterTts.setPitch);
await flutterTts.setLanguage("en-US");
//await flutterTts.setPitch(1.0);
//await flutterTts.speak(text);
await flutterTts.speak('hello how are you');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('tts'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Press this button to say hello',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async{
speak();
},
child: Column(
children: <Widget>[
Text('say hello',style: TextStyle(
fontSize: 20,
color: Colors.white,
),
)
],
),
)
],
),
)
],
),
);
}
}
I suggest testing the following on your current emulator setup, a real device, and genymotion/stacks emulator (all three things):
Does ANY audio play properly such as a youtube video, or sound settings demo?
If no, then STOP HERE: the problem has nothing to do with your code -- it has to do with the device, or in the case of an emulator, a bug with the way the emulator is using the audio hardware of the host device.
Does the tts engine demo test work properly in the devices settings?
If no, then STOP HERE: the problem is with the tts engine on the device.
Does your app work properly?
If no, then the problem could be your code. (but if you've already passed stages 1 and 2, then I very much doubt this will fail).
PS - If your app works on a real device then you really don't have a problem.
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.
When I want to do "Extract to widget", it raises an error : "reference to an enclosing class method cannot be extracted"
I know there is some variables that must get their data from class constructor but I want Android studio to extract the widget then, I will correct the mistaken codes, like Visual Studio that without any error extract the code to a new widget then it needs to copy the new extracted widget to a new dart file and correct the mistakes.
I want to extract the Card widget part.
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as prefix0;
import 'package:intl/intl.dart';
import '../model/transaction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
final Function deleteTx;
TransactionList(this.transactions, this.deleteTx);
#override
Widget build(BuildContext context) {
return transactions.isEmpty
? LayoutBuilder(
builder: (ctx, constraint) {
return Column(
children: <Widget>[
Text(
'There is no transaction',
style: Theme.of(context).textTheme.title,
textDirection: prefix0.TextDirection.rtl,
),
SizedBox(
height: 10,
),
Container(
height: constraint.maxHeight * 0.6,
child: Image.asset(
'assets/images/yalda.png',
fit: BoxFit.cover,
))
],
);
},
)
: ListView.builder(
itemCount: transactions.length,
itemBuilder: (ctx, index) {
return **Card**(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 5),
elevation: 5,
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: const EdgeInsets.all(8),
child: FittedBox(
child: Text('\$${transactions[index].amount}')),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.title,
),
subtitle: Text(DateFormat.yMMMd()
.format(transactions[index].date)
.toString()),
trailing: MediaQuery.of(context).size.width > 360
? FlatButton.icon(
onPressed: () => deleteTx(transactions[index].id),
icon: const Icon(Icons.delete),
label: const Text('Delete'),
textColor: Theme.of(context).errorColor,
)
: IconButton(
icon: const Icon(Icons.delete),
color: Theme.of(context).errorColor,
onPressed: () => deleteTx(transactions[index].id),
),
),
);
});
}
}
Simply use "Extract Method" instead of "Extract Widget". VSCode will add all the returns and references.
Edit: If you want to use "Extract Widget" only then simply wrap that widget in a Container and then use "Extract Widget" on that widget.
If that doesn't work, comment out setState() function inside the widget and try again.
Your deleteTx might contain a setState(() {}) method, try to comment that part of your code where you're calling deleteTx it and just put it back after your extraction.
Just remove or comment the setState() {} from your widget and it gonna works.
transform onpressed etc. property to comments and then try again 'Extract Widget' and go on
I had the same issue and in my case it was because of ListView.builder as yours.
So it is easy to fix, Simply make a class and return Card in Widget build and return it in ListView.builder inside the TransactionList class with the desired arguments.
You have to care about a few things:
Whenever you are extracting a widget, that widget should not contain any variable which is used in the current working page.
All the functions or methods should be parametric.
It is because you are referencing a variable(for example, transactions) in your Card widget from the enclosing class i.e. TransactionList. The best way to extract in this case could be to just make stateless/stateful widget outside your class and cut the Card widget and paste it as the return type of the build method of that Widget you created. And you can reference those variables using the constructor of that widget you created.
If you can comment out deleteTx(transactions[index].id) parts of your code and then use onPressed: (){}, you will be able to extract to widget.
After the extraction you can use:
onPressed: (){
setState(() {
deleteTx(transactions[index].id);
});
}
there might be some local referance to the variable in the current class,so if there some referance we cant extract a widget from there.
You can use the "Extract Method". It's a simple way. VSCode will add all the returns and references.
If we extract the widget it will StatelessWidget. StatelessWidget doesn't support changing state so if you use any Onchange property SetState it never extract
so please remove setState(() {});
Just remove or comment the setState() {} from your widget
Or
Just remove or comment the MediaQuery.of(context).size.width from your widget
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);
}
}
I want to build a 'Nightstand Clock' app, and I want the phone to display the clock as long as the app is active without turning off the screen.
Is there a way to do this in Flutter?
I found this SO answer, but using the 'screen' plugin didn't work for me.
After adding the dependency to 'pubspecc.yaml' and running flutter packages get my app doesn't run anymore and Android SDK is getting stuck at the 'resolving dependencies' stage.
Either way, is there any other way to do this in flutter except the 'screen' plugin?
From the same SO post,it mentioned that the screen plugin encountered some issues. I've checked the plugin and it seems that it was not updated since March 13, 2019. Another plugin that would give the same function you needed is wakelock plugin. It is still available currently maintained by the author. In fact, latest version 0.5.0+2 was release last March 7, 2021.
Hi, I am still maintaining it :) We recently added macOS support as
well 🚀 Also, Flutter is open source - they have first-party plugins,
however, they do say themselves that they will abandon their
first-party solutions if a better third party project exists. So why
would they want to create one for something that works perfectly fine?
– creativecreatorormaybenot Feb 8 at 16:17
I've tested the sample given in the wakelock package:
import 'package:flutter/material.dart';
import 'package:wakelock/wakelock.dart';
void main() {
runApp(WakelockExampleApp());
}
class WakelockExampleApp extends StatefulWidget {
#override
_WakelockExampleAppState createState() => _WakelockExampleAppState();
}
class _WakelockExampleAppState extends State<WakelockExampleApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Wakelock example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
const Spacer(
flex: 3,
),
OutlinedButton(
onPressed: () {
setState(() {
Wakelock.enable();
});
},
child: const Text('enable wakelock'),
),
const Spacer(),
OutlinedButton(
onPressed: () {
setState(() {
Wakelock.disable();
});
},
child: const Text('disable wakelock'),
),
const Spacer(
flex: 2,
),
FutureBuilder(
future: Wakelock.enabled,
builder: (context, AsyncSnapshot<bool> snapshot) {
final data = snapshot.data;
if (data == null) {
return Container();
}
return Text('The wakelock is currently '
'${data ? 'enabled' : 'disabled'}.');
},
),
const Spacer(
flex: 3,
),
],
),
),
),
);
}
}
Here is the output in Android:
Output in iOS:
Also, it seems that you've resolved the previous issue in your code. It would be nice to share a minimal, complete and verifiable example for the community to understand the issue very well.