play sound in folder inside assets in flutter - audio

I have sound in this path assets/sounds/numbers
this code don't work
IconButton(
onPressed: () async {
final player=AudioPlayer();
await player.play(AssetSource('number_five_sound.mp3'));
},

Related

How to change AppBar's automaticallyImplyLeading property via a Consumer

As someone new to Flutter/Dart, I have a simplistic proof-of-concept web app (code provided below) where I've genuinely put the effort in to reading & prototyping but cannot quite get the code finished.
The app is a test of named routes. FirstScreen uses an ElevatedButton to jump to SecondScreen. SecondScreen can only return to FirstScreen via the Back arrow in SecondScreen's AppBar, but I also want the ability to dynamically hide that Back arrow if the app is started from SecondScreen, or enable it if the app is started from FirstScreen. Why ? Because the idea is to provide the option to run SecondScreen in a kiosk mode where the user's navigation is restricted to that one route of the app.
I designed the code to use a ChangeNotifier/Consumer approach using Flutter's "provider" package. The state is provided by the routedViaHome boolean (default is false) in RouteMonitor. The only time the boolean should be set true is if the app starts at FirstScreen and the user clicks the ElevatedButton to go to SecondScreen; that change is observed by SecondScreen and should be used to dynamically set its own AppBar 'automaticallyImplyLeading' property.
My question is this: the Consumer is correctly displaying the Text widget, but how do I ALSO get it to update the automaticallyImplyLeading property ? What am I missing please and/or have I needlessly complicated this ?
Thank you !
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => RouteMonitor(),
child: const MyApp(),
)
);
}
class RouteMonitor with ChangeNotifier {
bool routedViaHome = false;
void routeViaHome() {
routedViaHome = true;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => const FirstScreen(),
'/second': (context) => const SecondScreen(),
},
);
}
}
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Provider.of<RouteMonitor>(context, listen: false).routeViaHome();
Navigator.pushNamed(context, '/second');
//Navigator.pushReplacementNamed(context, '/second');
},
child: const Text('Launch screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Screen'),
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This is static data but no navigation'),
Consumer<RouteMonitor>(
builder: (context, routemonitor, child) => Text(
'${routemonitor.routedViaHome}',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
);
}
}

uploading images server using graphql apis

i want to upload my images to the sever from flutter web, which is using graphql api. i am able to show the images on the web but unable to upload images to the server.
static Future<int> multipartApi(File file)async {
print("image_file_path=${file.path}");
var byteData = file.readAsBytesSync();
var multipartFile = MultipartFile.fromBytes(
"",
byteData,
filename: "${DateTime.now().second}.jpeg",
contentType: MediaType("image", "jpeg"),
);
here i am picking images from gallery
final picker = ImagePicker();
List<Uint8List> images = []; // <----change this
List<Uint8List> imageFiles = [];
List<File> imageList = [];
List<int> my_images = [];
pickImage(BuildContext context) async {
List<XFile>? files = await picker.pickMultiImage(imageQuality: 50);
if (files != null) {
for (var element in files) {
imageList.add(File(element.path));
print("imageList= ${imageList.first.path}");
html.File filePath = html.File(element.path.codeUnits, element.path);
print("filePath: ${filePath.toString()}");
imageFiles.add(await element.readAsBytes());
}}
// for (var element in files!) {
// imageList.add(File(element.path));
//
// imageFiles.add(await element.readAsBytes()); // <----change this
// }
print("image path: ${imageList}");
print("Length of images: ${imageList.length}");
setState(() {
images = imageFiles;
print("selected_images: ${images.first.toString()}");
});
print("list length: ${images.length}");
}
and here i am displaying my images inside listview builder.
child: ListView.builder(
itemCount: images.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Image.memory(
images[index],
height: 80,
width: 80,
),
InkWell(
onTap: () {
setState(() {
images.remove(images[index]);
});
},
child: const Icon(Icons.close),
),
],
);
},
),
tell me where i am wrong.

I am sending the GET request to the flutter app from the express API but I am not getting any output

I am sending the GET request to the flutter app from the express API but I am not getting any output in the flutter App. The API is working in the postman and I am getting the perfect output in the postman.
Please help
testing() async{
debugPrint("Hello");
http.Response response = await
http.get("http://192.168.119.97:3000/api/cricketer");
debugPrint((response.body));
debugPrint("Hello hy");
}
Future getData() async {
http.Response response = await
http.get("http://192.168.119.97:3000/api/cricketer");
debugPrint((response.body));
data = json.decode(response.body);
debugPrint(('$data'));
setState(() {
userData = data["cricketers"];
debugPrint("Hello ");
debugPrint(('$userData'));
});
}
Calling the Function:
#override
void initState() {
super.initState();
getData();
testing();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cricketer Info"),
backgroundColor: Colors.pink,
),
body: ListView.builder(
itemCount: userData == null ? 0 : userData.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: <Widget>[
// CircleAvatar(
// backgroundImage: NetworkImage(userData[index][""]),
// ),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text("${userData[index]["name"]}",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w700,
),),
)
],
),
),
);
},
),
);
}
}
I have uploaded the code also. Please check and if possible help
First, you have to JSON decode the body for print, json.decode() gives some misleading. You can use jsonDecode(result.body) from 'dart:convert' package . Here I have attached some
example codes of login(Post request). After decoding you can use a data model and factory method to convert to a dart object.
repo dart file that send post request
my data model with a factory method for decode json to dart

Flutter show download failed with java.lang.IllegalArgumentException after downloading 100%

I am trying to make a wallpaper app to download images but it shows download failed when it completes download with error Couldn't find meta-data for provider with authority. I am downloading with flutter-downloader package.
Thanks.
java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority
sagarrawatuk.fotoApp.flutter_downloader.provider
class _ImagePathState extends State<ImagePath> {
String localPath;
Future<String> get localpath async {
final result = await Permission.storage.request();
if (result == PermissionStatus.granted) {
final localPath =
(await findLocalPath()) + Platform.pathSeparator + 'Download';
final savedDir = Directory(localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
return localPath;
} else
return null;
}
Future<String> findLocalPath() async {
final directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
return directory.path;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: myColor,
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
color: Colors.black,
),
actions: [
IconButton(
color: Colors.black,
icon: Icon(Icons.file_download),
onPressed: () async => DownloadTask(
taskId: await FlutterDownloader.enqueue(
url: widget.imgPath,
savedDir: await localpath,
showNotification: true)))
],
),
body: SizedBox.expand(
child: Container(
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Hero(
tag: widget.imgPath, child: Image.network(widget.imgPath)),
),
],
),
),
),
);
}
Add provider in 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>
See docs https://pub.dev/packages/flutter_downloader#android-integration

Displaying questions from API one at a time in Flutter

i want to display the questions i get from an API one by one. I call the API, parse and store the data, but i don't know how to display each question separately. I can put them in a list view but that's about it. I have a widget with FutureBuilder that calls the API, and i'm currently trying to send data to another widget and manipulate it there using another FutureBuilder (so that i don't keep calling the API when i iterate through the list of questions to display them). I have an integer to keep track of the current position. How should i go about doing this?
Part of the code:
Here i'm trying to send the data to another widget.
FutureBuilder<Reply>(
future: questions(token, id),
builder: (context, snapshot) {
if (snapshot.hasError) {
print('Error : ${snapshot.error}'); //show error on the terminal
return Text('Error : ${snapshot.error}'); //show error on the app
} else if (snapshot.hasData) {
reply = snapshot.data;
return Show_Questions(reply: reply,);
} else {
return Center(child: CircularProgressIndicator()); //else display a loading indicator
} //loading indicator
}
),
Any help is appreciated. I can post more code if needed.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new FutureBuilder(
future: questions(token, id),
initialData: [],
builder: (context, snapshot) {
return createListView(context, snapshot);
}),
);
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
var values = snapshot.data;
return ListView.builder(
itemCount: values == null ? 0 : values.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
});
},
child: Column(
children: <Widget>[
new ListTile(
title: Text(values[index]),
),
Divider(
height: 2.0,
),
],
),
);
},
);
}
}
hopefully help you :)

Resources