I want to filter using CheckboxListTile in flutter but i have not showing any reflection of filtering in listview when i use Alert dialog? - flutter

I filter the one litview builder list to another checkbox list and this is working, but when i add this CheckboxListTile in Alert dialog when no filter reflection showing.
I used StatefulBuilder also but is not useful to filtering listview.
[This is first link to show Product list data][1]
This is second link of filter list
I am stuck in how to one data filter to another item filter that availiable in Alert dialog.
This is Api link
const String baseUrl = "https://run.mocky.io/v3/";
const String productDataUrl = baseUrl + "4ecbd2ea-a725-438b-b8fc-da8fc08bc875";
const String productCategoryDataUrl =
baseUrl + "0595387e-732e-47cf-9675-244fed9fc014";
This is product model class that listview model that we want to filter
class ProductDataModel {
int? productId;
String? productName;
int? productPrice;
int? productKG;
String? productCategoryId;
ProductDataModel(
{this.productId,
this.productName,
this.productPrice,
this.productKG,
this.productCategoryId});
ProductDataModel.fromJson(Map<String, dynamic> json) {
productId = json['ProductId'];
productName = json['ProductName'];
productPrice = json['ProductPrice'];
productKG = json['ProductKG'];
productCategoryId = json['ProductCategoryId'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ProductId'] = this.productId;
data['ProductName'] = this.productName;
data['ProductPrice'] = this.productPrice;
data['ProductKG'] = this.productKG;
data['ProductCategoryId'] = this.productCategoryId;
return data;
}
}
This ProductCategory Model class for using filter and this model class
data in CheckboxTile
class ProductCategoryDataModel {
int? productCategoryId;
String? productCategoryName;
bool? isChecked=false;
ProductCategoryDataModel(
{this.productCategoryId, this.productCategoryName, this.isChecked});
ProductCategoryDataModel.fromJson(Map<String, dynamic> json) {
productCategoryId = json['ProductCategoryId'];
productCategoryName = json['ProductCategoryName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['ProductCategoryId'] = this.productCategoryId;
data['ProductCategoryName'] = this.productCategoryName;
return data;
}
}
This is code of showing listview and filter data using
checkboxlisttile that data in Alert dialog .
import 'dart:convert';
import 'dart:developer';
import 'package:dummy_checkbox_filter_list/commons/api_url.dart';
import 'package:dummy_checkbox_filter_list/model/product_category_data_model.dart';
import 'package:dummy_checkbox_filter_list/model/product_data_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<ProductDataModel> productDataList = [];
Set<ProductDataModel> productDataListDisplay = {};
List<ProductCategoryDataModel> productCategoryDataList = [];
List<ProductCategoryDataModel> selectProductCategoryDataList = [];
ScrollController scrollController = ScrollController();
bool isShowLoader = false;
getProductList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=> ${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productDataList.add(ProductDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
getProductCategoryList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productCategoryDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=>${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productCategoryDataList
.add(new ProductCategoryDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productCategoryDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
#override
void initState() {
getProductList();
getProductCategoryList();
super.initState();
}
#override
Widget build(BuildContext context) {
filterProduct(productDataList);
return Scaffold(
body: SafeArea(
child: isShowLoader == false
? SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
titlePadding: EdgeInsets.zero,
backgroundColor: Color(0xFF242424),
title: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
Icons.close,
color: Colors.white,
size: 25,
))
],
),
contentPadding: EdgeInsets.zero,
content: Container(
padding: EdgeInsets.all(5),
width: double.maxFinite,
child: ListView(
padding: EdgeInsets.all(8.0),
children: [
Text(
"dfff "+productCategoryDataList[0].isChecked.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 16),
),
...productCategoryDataList
.map((e) => CheckboxListTile(
controlAffinity:
ListTileControlAffinity
.leading,
title: Text(
"${e.productCategoryName}",
style: TextStyle(
color: Colors.white,
fontSize: 16),
),
value: e.isChecked,
selected:
selectProductCategoryDataList
.contains(e),
onChanged: (val) {
print("val: "+val.toString());
setState(() {
e.isChecked = val;
selectProductCategoryDataList
.contains(e)
? selectProductCategoryDataList
.remove(e)
: selectProductCategoryDataList
.add(e);
print(
"_isChecked: ${e.isChecked}");
});
},
))
],
),
),
);
},
);
});
},
style: ElevatedButton.styleFrom(
primary: Colors.black,
onPrimary: Colors.white,
minimumSize: Size(
MediaQuery.of(context).size.width * 0.30,
MediaQuery.of(context).size.height * 0.05)),
child: Text(
"Filter",
style: TextStyle(fontSize: 15),
),
),
Container(
child: ListView.builder(
itemCount: productDataListDisplay.length,
shrinkWrap: true,
controller: scrollController,
itemBuilder: (context, index) {
return Card(
child: Container(
padding: EdgeInsets.only(top: 15, bottom: 15),
color: (index % 2 == 0)
? Colors.grey.shade100
: Colors.white,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(productDataListDisplay
.elementAt(index)
.productId
.toString()),
Center(
child: Text(
productDataListDisplay
.elementAt(index)
.productName
.toString(),
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productKG.toString()} KG",
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
),
),
],
),
),
);
},
),
),
],
),
)
: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
),
),
);
}
void filterProduct(allProducts) {
productDataListDisplay.clear();
if (selectProductCategoryDataList != null &&
selectProductCategoryDataList.isNotEmpty) {
final List<int> idsOfSelectedCategories = selectProductCategoryDataList
.map((category) => category.productCategoryId!)
.toList();
print("idsOfSelectedCategories=> $idsOfSelectedCategories");
Set<ProductDataModel> storesInSelectedCategories =
getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
setState(() {
productDataListDisplay.addAll(storesInSelectedCategories);
print(allProducts.length);
print(storesInSelectedCategories.length);
});
} else {
setState(() {
productDataListDisplay.addAll(allProducts);
});
}
}
Set<ProductDataModel> getStoresFromSelectedCategories(
List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
Set<ProductDataModel> allProductsFromCategory = {};
for (var categoryId in idsOfSelectedCategories) {
var productMatched = allProducts
.where((store) => store.productCategoryId!
.split(" ")
.contains(categoryId.toString()))
.toList();
print("Stores Matched runtime=>${productMatched.runtimeType}");
allProductsFromCategory.addAll(productMatched);
}
return allProductsFromCategory;
}
}

Add .then((value) {if (mounted) {setState(() {});}}); to showdialog so that state gets refreshed when alertdialog closes.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<ProductDataModel> productDataList = [];
Set<ProductDataModel> productDataListDisplay = {};
List<ProductCategoryDataModel> productCategoryDataList = [];
List<ProductCategoryDataModel> selectProductCategoryDataList = [];
ScrollController scrollController = ScrollController();
bool isShowLoader = false;
getProductList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=> ${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productDataList.add(ProductDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
getProductCategoryList() async {
try {
setState(() {
isShowLoader = true;
});
final response = await http.get(Uri.parse(productCategoryDataUrl));
log("Response URL=> ${response.toString()}");
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
log("Response Body=>${decode.toString()}");
for (int i = 0; i < decode.length; i++) {
productCategoryDataList
.add(new ProductCategoryDataModel.fromJson(decode[i]));
}
setState(() {
isShowLoader = false;
});
return productCategoryDataList;
} else {
setState(() {
isShowLoader = false;
});
throw "Unable to retrieve product data.";
}
} catch (e) {
setState(() {
isShowLoader = false;
});
print('Something went wrong.');
}
}
#override
void initState() {
getProductList();
getProductCategoryList();
super.initState();
}
#override
Widget build(BuildContext context) {
filterProduct(productDataList);
return Scaffold(
body: SafeArea(
child: isShowLoader == false
? SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
titlePadding: EdgeInsets.zero,
backgroundColor: const Color(0xFF242424),
title: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(
Icons.close,
color: Colors.white,
size: 25,
))
],
),
contentPadding: EdgeInsets.zero,
content: Container(
padding: EdgeInsets.all(5),
width: double.maxFinite,
child: ListView(
padding: EdgeInsets.all(8.0),
children: [
Text(
"dfff ${productCategoryDataList[0].isChecked}",
style: const TextStyle(
color: Colors.white,
fontSize: 16),
),
...productCategoryDataList
.map((e) => CheckboxListTile(
controlAffinity:
ListTileControlAffinity
.leading,
title: Text(
"${e.productCategoryName}",
style: const TextStyle(
color: Colors.white,
fontSize: 16),
),
value: e.isChecked,
selected:
selectProductCategoryDataList
.contains(e),
onChanged: (val) {
print("val: $val");
setState(() {
e.isChecked = val;
selectProductCategoryDataList
.contains(e)
? selectProductCategoryDataList
.remove(e)
: selectProductCategoryDataList
.add(e);
print(
"_isChecked: ${e.isChecked}");
});
},
))
],
),
),
);
},
);
}).then((value) {
if (mounted) {
setState(() {});
}
});
},
style: ElevatedButton.styleFrom(
primary: Colors.black,
onPrimary: Colors.white,
minimumSize: Size(
MediaQuery.of(context).size.width * 0.30,
MediaQuery.of(context).size.height * 0.05)),
child: const Text(
"Filter",
style: TextStyle(fontSize: 15),
),
),
Container(
child: ListView.builder(
itemCount: productDataListDisplay.length,
shrinkWrap: true,
controller: scrollController,
itemBuilder: (context, index) {
return Card(
child: Container(
padding: EdgeInsets.only(top: 15, bottom: 15),
color: (index % 2 == 0)
? Colors.grey.shade100
: Colors.white,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(productDataListDisplay
.elementAt(index)
.productId
.toString()),
Center(
child: Text(
productDataListDisplay
.elementAt(index)
.productName
.toString(),
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productKG.toString()} KG",
),
),
Center(
child: Text(
"${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
),
),
],
),
),
);
},
),
),
],
),
)
: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
),
),
);
}
void filterProduct(allProducts) {
productDataListDisplay.clear();
if (selectProductCategoryDataList != null &&
selectProductCategoryDataList.isNotEmpty) {
final List<int> idsOfSelectedCategories = selectProductCategoryDataList
.map((category) => category.productCategoryId!)
.toList();
print("idsOfSelectedCategories=> $idsOfSelectedCategories");
Set<ProductDataModel> storesInSelectedCategories =
getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
setState(() {
productDataListDisplay.addAll(storesInSelectedCategories);
print(allProducts.length);
print(storesInSelectedCategories.length);
});
} else {
setState(() {
productDataListDisplay.addAll(allProducts);
});
}
}
Set<ProductDataModel> getStoresFromSelectedCategories(
List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
Set<ProductDataModel> allProductsFromCategory = {};
for (var categoryId in idsOfSelectedCategories) {
var productMatched = allProducts
.where((store) => store.productCategoryId!
.split(" ")
.contains(categoryId.toString()))
.toList();
print("Stores Matched runtime=>${productMatched.runtimeType}");
allProductsFromCategory.addAll(productMatched);
}
return allProductsFromCategory;
}
}

Related

Failed host lookup from rest.coinapi.io

I am trying to fetch network data from the coinAPI to get the exchange rate for 1btc to usd.. but after fetching the api and awaiting it in price screen so the ui will give the exchange rate... I get failed host lookup
This is the coin_data.dart file... contains the api and networking
import 'dart:convert';
import 'package:http/http.dart' as http;
const List<String> currenciesList = [
'AUD',
'BRL',
'CAD',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'ILS',
'INR',
'JPY',
'MXN',
'NOK',
'NZD',
'PLN',
'RON',
'RUB',
'SEK',
'SGD',
'USD',
'ZAR'
];
const List<String> cryptoList = [
'BTC',
'ETH',
'LTC',
];
const coinAPIUrl = 'https://rest.coinapi.io/v1/exchangerate';
const apiKey = 'APIKEY';
class CoinData {
Future<dynamic> getCoinData() async {
// http.Response response = await http.get(Uri.parse('$coinAPIUrl/BTC/USD?apikey=$apiKey'));
http.Response response = await http.get(Uri.parse('$coinAPIUrl/BTC/USD?apikey=$apiKey'));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
var lastPrice = decodedData['rate'];
return lastPrice;
} else {
print(response.statusCode);
throw 'Problem with the get request';
}
}
}
This is the price_screen.dart file.. the actual UI and display of the exchange rate
import 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ticker_bitcoin/coin_data.dart';
class PriceScreen extends StatefulWidget {
const PriceScreen({super.key});
#override
State<PriceScreen> createState() => _PriceScreenState();
}
class _PriceScreenState extends State<PriceScreen> {
late String selectedCurrency = 'USD';
DropdownButton<String> androidDropdown() {
List<DropdownMenuItem<String>> dropdownItems = [];
for (int i = 0; i < currenciesList.length; i++) {
String currency = currenciesList[i];
var newItem = DropdownMenuItem(
value: currency,
child: Text(currency),
);
dropdownItems.add(newItem);
}
return DropdownButton(
value: selectedCurrency,
items: dropdownItems,
onChanged: (value) {
setState(() {
selectedCurrency = value!;
});
},
);
}
CupertinoPicker iOSPicker() {
List<Text> pickerItems = [];
for (String currency in currenciesList) {
Text(currency);
pickerItems.add(Text(currency));
}
return CupertinoPicker(
itemExtent: 32.0,
onSelectedItemChanged: (selectedIndex) {
print(selectedIndex);
},
children: pickerItems,
);
}
// Widget getPicker() {
// if (Platform.isIOS) {
// return iOSPicker();
// } else if (Platform.isAndroid) {
// return androidDropdown();
// }
// return getPicker();
// }
String bitcoinValueInUSD = '?';
void getData() async {
try {
double data = await CoinData().getCoinData();
setState(() {
bitcoinValueInUSD = data.toStringAsFixed(0);
});
} catch (e) {
print(e);
}
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('🤑 Coin Ticker'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
child: Card(
color: Colors.lightBlueAccent,
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
child: Text(
'1 BTC = $bitcoinValueInUSD USD',
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
),
),
),
Container(
height: 125.0,
alignment: Alignment.center,
padding: const EdgeInsets.only(bottom: 30.0),
color: Colors.lightBlue,
child: Platform.isIOS ? iOSPicker() : androidDropdown(),
),
],
),
);
}
}
It means your device/emulator got disconnected to the internet. If your host is connected to internet but emulator is disconnected then a cold reboot will do the trick. You'll find that under Device Manager > vertical ellipsis (â‹®) > Cold Boot Now button.

Video player play image and video looping flutter

can video player play image for 10sec then loop to next video ?
How can i loop image only for 10sec then loop into next new video in my video clip data or video player controller ?
I manage to add video to video player but don't know how to add image to the player.
video clip data
class VideoClip {
final String fileName;
final String thumbName;
final String title;
final String parent;
int runningTime;
VideoClip(this.title, this.fileName, this.thumbName, this.runningTime, this.parent);
String videoPath() {
return "$parent/$fileName";
}
String thumbPath() {
return "$parent/$thumbName";
}
static List<VideoClip> remoteClips = [
VideoClip("For Bigger Fun", "ForBiggerFun.mp4", "images/ForBiggerFun.jpg", 0, "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample"),
VideoClip("Elephant Dream", "ElephantsDream.mp4", "images/ForBiggerBlazes.jpg", 0, "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample"),
VideoClip("BigBuckBunny", "BigBuckBunny.mp4", "images/BigBuckBunny.jpg", 0, "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample"),
];
}
Video player controller
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_video_list_sample/clips.dart';
import 'package:video_player/video_player.dart';
import 'package:wakelock/wakelock.dart';
class PlayPage extends StatefulWidget {
PlayPage({Key key, #required this.clips}) : super(key: key);
final List<VideoClip> clips;
#override
_PlayPageState createState() => _PlayPageState();
}
class _PlayPageState extends State<PlayPage> {
VideoPlayerController _controller;
List<VideoClip> get _clips {
return widget.clips;
}
var _playingIndex = -1;
var _disposed = false;
var _isFullScreen = false;
var _isEndOfClip = false;
var _progress = 0.0;
var _showingDialog = false;
Timer _timerVisibleControl;
double _controlAlpha = 1.0;
var _playing = false;
bool get _isPlaying {
return _playing;
}
set _isPlaying(bool value) {
_playing = value;
_timerVisibleControl?.cancel();
if (value) {
_timerVisibleControl = Timer(Duration(seconds: 2), () {
if (_disposed) return;
setState(() {
_controlAlpha = 0.0;
});
});
} else {
_timerVisibleControl = Timer(Duration(milliseconds: 200), () {
if (_disposed) return;
setState(() {
_controlAlpha = 1.0;
});
});
}
}
void _onTapVideo() {
debugPrint("_onTapVideo $_controlAlpha");
setState(() {
_controlAlpha = _controlAlpha > 0 ? 0 : 1;
});
_timerVisibleControl?.cancel();
_timerVisibleControl = Timer(Duration(seconds: 2), () {
if (_isPlaying) {
setState(() {
_controlAlpha = 0.0;
});
}
});
}
#override
void initState() {
Wakelock.enable();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
_initializeAndPlay(0);
super.initState();
}
#override
void dispose() {
_disposed = true;
_timerVisibleControl?.cancel();
Wakelock.disable();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
_exitFullScreen();
_controller?.pause(); // mute instantly
_controller?.dispose();
_controller = null;
super.dispose();
}
void _toggleFullscreen() async {
if (_isFullScreen) {
_exitFullScreen();
} else {
_enterFullScreen();
}
}
void _enterFullScreen() async {
debugPrint("enterFullScreen");
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
await SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
if (_disposed) return;
setState(() {
_isFullScreen = true;
});
}
void _exitFullScreen() async {
debugPrint("exitFullScreen");
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
if (_disposed) return;
setState(() {
_isFullScreen = false;
});
}
void _initializeAndPlay(int index) async {
print("_initializeAndPlay ---------> $index");
final clip = _clips[index];
final controller = clip.parent.startsWith("http")
? VideoPlayerController.network(clip.videoPath())
: VideoPlayerController.asset(clip.videoPath());
final old = _controller;
_controller = controller;
if (old != null) {
old.removeListener(_onControllerUpdated);
old.pause();
debugPrint("---- old contoller paused.");
}
debugPrint("---- controller changed.");
setState(() {});
controller
..initialize().then((_) {
debugPrint("---- controller initialized");
old?.dispose();
_playingIndex = index;
_duration = null;
_position = null;
controller.addListener(_onControllerUpdated);
controller.play();
setState(() {});
});
}
var _updateProgressInterval = 0.0;
Duration _duration;
Duration _position;
void _onControllerUpdated() async {
if (_disposed) return;
// blocking too many updation
// important !!
final now = DateTime.now().millisecondsSinceEpoch;
if (_updateProgressInterval > now) {
return;
}
_updateProgressInterval = now + 500.0;
final controller = _controller;
if (controller == null) return;
if (!controller.value.isInitialized) return;
if (_duration == null) {
_duration = _controller.value.duration;
}
var duration = _duration;
if (duration == null) return;
var position = await controller.position;
_position = position;
final playing = controller.value.isPlaying;
final isEndOfClip = position.inMilliseconds > 0 && position.inSeconds + 1 >= duration.inSeconds;
if (playing) {
// handle progress indicator
if (_disposed) return;
setState(() {
_progress = position.inMilliseconds.ceilToDouble() / duration.inMilliseconds.ceilToDouble();
});
}
// handle clip end
if (_isPlaying != playing || _isEndOfClip != isEndOfClip) {
_isPlaying = playing;
_isEndOfClip = isEndOfClip;
debugPrint("updated -----> isPlaying=$playing / isEndOfClip=$isEndOfClip");
if (isEndOfClip && !playing) {
debugPrint("========================== End of Clip / Handle NEXT ========================== ");
final isComplete = _playingIndex == _clips.length - 1;
if (isComplete) {
print("played all!!");
if (!_showingDialog) {
_showingDialog = true;
_showPlayedAllDialog().then((value) {
_exitFullScreen();
_showingDialog = false;
});
}
} else {
_initializeAndPlay(_playingIndex + 1);
}
}
}
}
Future<bool> _showPlayedAllDialog() async {
return showDialog<bool>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
content: SingleChildScrollView(child: Text("Played all videos.")),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text("Close"),
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _isFullScreen
? null
: AppBar(
title: Text("Play View"),
),
body: _isFullScreen
? Container(
child: Center(child: _playView(context)),
decoration: BoxDecoration(color: Colors.black),
)
: Column(children: <Widget>[
Container(
child: Center(child: _playView(context)),
decoration: BoxDecoration(color: Colors.black),
),
Expanded(
child: _listView(),
),
]),
);
}
void _onTapCard(int index) {
_initializeAndPlay(index);
}
Widget _playView(BuildContext context) {
final controller = _controller;
if (controller != null && controller.value.isInitialized) {
return AspectRatio(
//aspectRatio: controller.value.aspectRatio,
aspectRatio: 16.0 / 9.0,
child: Stack(
children: <Widget>[
GestureDetector(
child: VideoPlayer(controller),
onTap: _onTapVideo,
),
_controlAlpha > 0
? AnimatedOpacity(
opacity: _controlAlpha,
duration: Duration(milliseconds: 250),
child: _controlView(context),
)
: Container(),
],
),
);
} else {
return AspectRatio(
aspectRatio: 16.0 / 9.0,
child: Center(
child: Text(
"Preparing ...",
style: TextStyle(color: Colors.white70, fontWeight: FontWeight.bold, fontSize: 18.0),
)),
);
}
}
Widget _listView() {
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
itemCount: _clips.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
borderRadius: BorderRadius.all(Radius.circular(6)),
splashColor: Colors.blue[100],
onTap: () {
_onTapCard(index);
},
child: _buildCard(index),
);
},
).build(context);
}
Widget _controlView(BuildContext context) {
return Column(
children: <Widget>[
_topUI(),
Expanded(
child: _centerUI(),
),
_bottomUI()
],
);
}
Widget _centerUI() {
return Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () async {
final index = _playingIndex - 1;
if (index > 0 && _clips.length > 0) {
_initializeAndPlay(index);
}
},
child: Icon(
Icons.fast_rewind,
size: 36.0,
color: Colors.white,
),
),
TextButton(
onPressed: () async {
if (_isPlaying) {
_controller?.pause();
_isPlaying = false;
} else {
final controller = _controller;
if (controller != null) {
final pos = _position?.inSeconds ?? 0;
final dur = _duration?.inSeconds ?? 0;
final isEnd = pos == dur;
if (isEnd) {
_initializeAndPlay(_playingIndex);
} else {
controller.play();
}
}
}
setState(() {});
},
child: Icon(
_isPlaying ? Icons.pause : Icons.play_arrow,
size: 56.0,
color: Colors.white,
),
),
TextButton(
onPressed: () async {
final index = _playingIndex + 1;
if (index < _clips.length - 1) {
_initializeAndPlay(index);
}
},
child: Icon(
Icons.fast_forward,
size: 36.0,
color: Colors.white,
),
),
],
));
}
String convertTwo(int value) {
return value < 10 ? "0$value" : "$value";
}
Widget _topUI() {
final noMute = (_controller?.value?.volume ?? 0) > 0;
final duration = _duration?.inSeconds ?? 0;
final head = _position?.inSeconds ?? 0;
final remained = max(0, duration - head);
final min = convertTwo(remained ~/ 60.0);
final sec = convertTwo(remained % 60);
return Row(
children: <Widget>[
InkWell(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Container(
decoration: BoxDecoration(shape: BoxShape.circle, boxShadow: [
BoxShadow(offset: const Offset(0.0, 0.0), blurRadius: 4.0, color: Color.fromARGB(50, 0, 0, 0)),
]),
child: Icon(
noMute ? Icons.volume_up : Icons.volume_off,
color: Colors.white,
)),
),
onTap: () {
if (noMute) {
_controller?.setVolume(0);
} else {
_controller?.setVolume(1.0);
}
setState(() {});
},
),
Expanded(
child: Container(),
),
Text(
"$min:$sec",
style: TextStyle(
color: Colors.white,
shadows: <Shadow>[
Shadow(
offset: Offset(0.0, 1.0),
blurRadius: 4.0,
color: Color.fromARGB(150, 0, 0, 0),
),
],
),
),
SizedBox(width: 10)
],
);
}
Widget _bottomUI() {
return Row(
children: <Widget>[
SizedBox(width: 20),
Expanded(
child: Slider(
value: max(0, min(_progress * 100, 100)),
min: 0,
max: 100,
onChanged: (value) {
setState(() {
_progress = value * 0.01;
});
},
onChangeStart: (value) {
debugPrint("-- onChangeStart $value");
_controller?.pause();
},
onChangeEnd: (value) {
debugPrint("-- onChangeEnd $value");
final duration = _controller?.value?.duration;
if (duration != null) {
var newValue = max(0, min(value, 99)) * 0.01;
var millis = (duration.inMilliseconds * newValue).toInt();
_controller?.seekTo(Duration(milliseconds: millis));
_controller?.play();
}
},
),
),
IconButton(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
color: Colors.yellow,
icon: Icon(
Icons.fullscreen,
color: Colors.white,
),
onPressed: _toggleFullscreen,
),
],
);
}
Widget _buildCard(int index) {
final clip = _clips[index];
final playing = index == _playingIndex;
String runtime;
if (clip.runningTime > 60) {
runtime = "${clip.runningTime ~/ 60}분 ${clip.runningTime % 60}초";
} else {
runtime = "${clip.runningTime % 60}ì´ˆ";
}
return Card(
child: Container(
padding: EdgeInsets.all(4),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: 8),
child: clip.parent.startsWith("http")
? Image.network(clip.thumbPath(), width: 70, height: 50, fit: BoxFit.fill)
: Image.asset(clip.thumbPath(), width: 70, height: 50, fit: BoxFit.fill),
),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(clip.title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
Padding(
child: Text("$runtime", style: TextStyle(color: Colors.grey[500])),
padding: EdgeInsets.only(top: 3),
)
]),
),
Padding(
padding: EdgeInsets.all(8.0),
child: playing
? Icon(Icons.play_arrow)
: Icon(
Icons.play_arrow,
color: Colors.grey.shade300,
),
),
],
),
),
);
}
}

Flutter Firebase Realtime Database.Streambuilder and listview.builder returns error Index out of range: index should be less

i am using Flutter and Firebase to build an order app.I'm using Realtime Database and a streambuilder to fetch the data and every update and listview.builder to portray them.
When i display the data works fine but the problem is that when i am trying to expand the data in the RTDB i'm getting this error
Another exception was thrown: RangeError (index): Index out of range: index should be less than 22: 22.
I'm trying to expand the data on another page.Sorry if my question is a bit of a crap i am asking for the first time
Scaffold(
body: StreamBuilder(
stream: ref.onValue,
builder: (context, snapshot) {
if(
snapshot.hasData &&
snapshot.data != null &&
(snapshot.data! as DatabaseEvent).snapshot.children !=
null){
List<Orderlist> listorder = [];
final myorders = snapshot.data!.snapshot.children;
myorders.forEach((numoftable) {
count+=1;
String payment_state = '';
String payment_method = '';
List<Order> orders=[];
final number_of_orders = numoftable.children.length;
numoftable.children.forEach((order) {
if(order.key=='payment_state') payment_state=order.value.toString();
if(order.key=='payment_method') payment_method=order.value.toString();
List<Orderitem> orderitems = [];
final order_id = order.key.toString();
// print(order_id);
if(order_id.length<=3){
final node = order.value as Map<dynamic,dynamic>?;
String temp_pending='';
String temp_payment='';
String customer_uid='';
node!.forEach((keys,values) {
// orderitem.name = element;
if(keys!='description' && keys!='customer_uid'){
final value = values as Map<String,dynamic>;
String price='';
String description='';
String number_of_appereance='';
value.forEach((key, value) {
if(key=='price') price=value.toString();
if(key=='description') description=value;
if(key=='number of appereances') number_of_appereance = value.toString();
});
final orderitem = Orderitem(name: keys,price: price,description: description,number_of_appereance: number_of_appereance);
orderitems.add(orderitem);
}
if(keys=='description'){
temp_pending = values.toString();
}
if(keys=='customer_uid'){
customer_uid=values.toString();
}
},);
final nextorder = Order(number_of_table: int.tryParse(numoftable.key.toString()),
items: orderitems,order_ids: order_id,customer_uid: customer_uid,
pending: temp_pending,);
orders.add(nextorder);
}
});
final current_index = int.parse(numoftable.key.toString())-1;
`your text`
if(temp_length.isEmpty || count<=myorders.length){
temp_length.insert(current_index, orders.length);
}
else if(temp_length[current_index]<orders.length ){
temp_length[current_index]= orders.length;
ref.child(numoftable.key.toString()).update({'payment_state':'Not payed'});
ref.child(numoftable.key.toString()).update({'payment_method':'Cash'});
}
final nextorderlist = Orderlist(
orderlist: orders,
number_of_table: numoftable.key.toString(),
payment_state: payment_state,
payment_method: payment_method,
number_of_orders: number_of_orders);
// print(nextorder.order_ids);
listorder.add(nextorderlist);
// ref.child(numoftable.key.toString()).update({'check':'false'});
},
);
return Column(
children: [
GeneralSettings(),
Flexible(
child: GridView.builder(
shrinkWrap: true,
itemCount: listorder.length ,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (context, index) {
return _listoforders(listorder, index,);
},
),
),
],
);
}else if(snapshot.connectionState==ConnectionState.waiting){
Center(child: CircularProgressIndicator(),);
}
else if(snapshot.hasError){
return Text('Error');
}
return Text('Error');
}
),
);
}
Widget _listoforders(List<Orderlist> listoforders,int index) {
return GestureDetector(
onTap: (){
orders.clear();
listoforders[index].orderlist!.forEach((element) { orders.add(element); });
context.goNamed('Details');
},
child: Container(
color:listoforders[index].payment_state=='None' ? Colors.lightBlue : (listoforders[index].payment_state=='Not payed') ? Colors.red : Colors.green,
child: Column(
children: [
ListTile(title: Text(listoforders[index].number_of_table.toString()),
subtitle: listoforders[index].payment_state=='None' ? Icon(Icons.no_food) : listoforders[index].payment_state=='Not payed' ? Icon(Icons.money_off) : Text('Payed'),
trailing: IconButton(onPressed: () {
listoforders[index].orderlist!.forEach((element) {
setState(() {
temp_length[index]=0;
ref.child(listoforders[index].number_of_table.toString()).child(element.order_ids!).remove();
ref.child(listoforders[index].number_of_table.toString()).update({'payment_state':'None'});
ref.child(listoforders[index].number_of_table.toString()).update({'payment_method':'None'});
delete(element.customer_uid!);
});
});
}, icon: Icon(Icons.delete)),
leading: (listoforders[index].payment_method=='None' ) ? Text('No payment method') : (listoforders[index].payment_method=='With card' ) ? Icon(Icons.credit_card) : Icon(Icons.money_rounded),),
Flexible(
child: ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: listoforders[index].orderlist!.length,
itemBuilder: (context, current_index) {
final current_order = listoforders[index].orderlist![current_index];
return Container(
color: current_order.pending=='Unchecked' ? Colors.red : (current_order.pending=='pending') ? Colors.amber : Colors.green,
child: ListTile(
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (context)=>OrderSettings(order: current_order))),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(current_order.order_ids!),
],
),
subtitle: Text(current_order.pending!),
trailing: current_order.pending=='Unchecked' ? IconButton(onPressed: () => setState(() {
ref.child(current_order.number_of_table.toString()).child(current_order.order_ids!).update({"description":"pending"});
}) , icon: Icon(Icons.alarm_add)) :
current_order.pending=='pending' ? IconButton(onPressed: () => setState(() {
ref.child(current_order.number_of_table.toString()).child(current_order.order_ids!).update({"description":"Done"});
}) , icon: Icon(Icons.pending_actions)) : Icon(Icons.check),
leading: IconButton(onPressed:() {
ref.child(current_order.number_of_table.toString()).child(current_order.order_ids!).remove();
} ,
icon:Icon(Icons.delete) ,),
),
);
},),
),
],
),
),
);}
}
Future delete(String uid) async{
final doc = FirebaseFirestore.instance.collection('Customers').doc(uid);
await doc.update({'order':''});
}
I am updating the RTDB on this page
class UpdatePanel extends StatefulWidget {
String? name;
bool check;
int? tables;
UpdatePanel({super.key,this.name,required this.check, this.tables});
#override
State<UpdatePanel> createState() => _UpdatePanelState();
}
class _UpdatePanelState extends State<UpdatePanel> {
late DatabaseReference ref;
TextEditingController namecontroller = TextEditingController();
TextEditingController number_of_tables = TextEditingController();
#override
void initState() {
// TODO: implement initState
ref=FirebaseDatabase.instance.ref().child(widget.name!);
super.initState();
}
#override
Widget build(BuildContext context) {
print(widget.name);
print(widget.tables);
Size size = MediaQuery.of(context).size;
final futurefiles = FirebaseStorage.instance.ref().child('${widget.name}/');
return AlertDialog(
title: Text(widget.check? 'Update businness name':'Update tables number'),
content: Container(
height: size.height*0.3,
child: SingleChildScrollView(
child: Column(children: [
widget.check ?
Textwidget(controller: namecontroller, hinttext: 'Update name', labeltext: 'Name', icon: Icon(Icons.business_center), color: Colors.black) :
Textwidget(controller: number_of_tables, hinttext: 'Update number of tables', labeltext: 'Number of tables', icon: Icon(Icons.table_bar), color: Colors.black),
SizedBox(height: size.height*0.05,),
ElevatedButton.icon(onPressed: () {
setState(() {
DatabaseManager(displayName: widget.name).settabledata(int.parse(number_of_tables.text.trim()));
createQrcodes();
resetRTDB();
(context as Element).reassemble();
Navigator.pop(context);
});
}, icon: Icon(Icons.update), label: Text('Update'))
]),
),
),
actions: [
OutlinedButton(onPressed: () => Navigator.pop(context), child: Text('Close'))
],
);
}
void resetRTDB() async{
for(int i=widget.tables!+1;i<=int.parse(number_of_tables.text.trim());i++){
await ref.child('${i}').set({"payment_state":"None","payment_method":"None",});
}
}
Future<Uint8List> toQrImageData(String text) async {
try {
final image = await QrPainter(
data: text,
version: QrVersions.auto,
gapless: false,
color: Colors.black,
emptyColor: Colors.white,
).toImage(300);
final a = await image.toByteData(format: ImageByteFormat.png);
return a!.buffer.asUint8List();
} catch (e) {
throw e;
}
}
Future createQrcodes() async{
for(int i=widget.tables!+1;i<=int.parse(number_of_tables.text.trim());i++){
final path = '${widget.name!.trim()}/${i}';
final ref = FirebaseStorage.instance.ref().child(path);
final file = await toQrImageData(widget.name!.trim().toLowerCase()+' '+'${i}');
ref.putData(file,SettableMetadata(contentType: 'image/png'));
}
}
}
this is where your error occurs
void resetRTDB() async{
for(int i=widget.tables!+1;i<=int.parse(number_of_tables.text.trim());i++){
await ref.child('${i}').set({"payment_state":"None","payment_method":"None",});
}
after getting all the data and it tries to get new data by adding 1 in every time ,change try changing your logic here

Why does Flutter Camera Plugin return video content type as Application/octet-stream

hello guys!
i am using flutter story view package to implement story functionality in my app and i am using camera plugin to record video and upload, however the content type of the uploaded video is application/octet-stream when i receive it on my server and only when it is sent from ios. for android everything is fine and i get the content type as video/mp4.
can you guys please help me.
i have not done anything fancy i have just used the basic functionality of start recording and stop recording of the camra plugin.
// ignore_for_file: use_build_context_synchronously
List<CameraDescription>? cameras;
class CameraScreen extends StatefulWidget {
const CameraScreen({Key? key}) : super(key: key);
#override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
CameraController? _cameraController;
Future<void>? cameraValue;
bool flash = false;
bool iscamerafront = true;
static const _maxSeconds = 30;
ValueNotifier<bool> visible = ValueNotifier(false);
ValueNotifier<bool> isRecoring = ValueNotifier(false);
TimerProvider? _timerProvider;
#override
void initState() {
super.initState();
_timerProvider = Provider.of(context, listen: false);
_cameraController = CameraController(cameras![0], ResolutionPreset.veryHigh,
imageFormatGroup: ImageFormatGroup.bgra8888);
cameraValue = _cameraController?.initialize();
_cameraController?.prepareForVideoRecording();
lockCamera();
}
lockCamera() async {
await _cameraController!.lockCaptureOrientation();
}
#override
void dispose() {
super.dispose();
visible.dispose();
isRecoring.dispose();
_cameraController?.dispose();
}
#override
Widget build(BuildContext context) {
print("camera_screen");
final size = MediaQuery.of(context).size;
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
centerTitle: true,
title: ValueListenableBuilder<bool>(
valueListenable: visible,
builder: (context, value, child) {
return Visibility(
visible: value,
child: Container(
padding: const EdgeInsets.all(10),
width: 50,
height: 50,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withOpacity(0.5)),
child: Center(
child: Consumer<TimerProvider>(
builder: (context, value, child) {
if (value.seconds == 0) {
if (_cameraController!.value.isRecordingVideo) {
stopRecording();
}
}
return Text(
value.seconds.toString(),
style: CustomStyles.fixAppBarTextStyle
.copyWith(color: Colors.white),
);
}),
),
));
}),
backgroundColor: Colors.transparent,
leadingWidth: 100,
leading: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Cancel",
style: CustomStyles.fixMediumBodyTextStyle
.copyWith(color: Colors.white),
),
)),
),
),
body: SafeArea(
top: false,
child: Stack(
children: [
FutureBuilder(
future: cameraValue,
builder: (context, snapshot) {
_cameraController?.lockCaptureOrientation();
if (snapshot.connectionState == ConnectionState.done) {
return Transform.scale(
scale: size.aspectRatio *
_cameraController!.value.aspectRatio <
1
? 1 /
(size.aspectRatio *
_cameraController!.value.aspectRatio)
: size.aspectRatio *
_cameraController!.value.aspectRatio,
child: Center(child: CameraPreview(_cameraController!)),
);
} else {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
}),
Positioned(
bottom: 0.0,
child: Container(
padding: const EdgeInsets.only(top: 5, bottom: 5),
width: Dimensions.screenWidth,
child: Column(
children: [
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withOpacity(0.5)),
child: Center(
child: IconButton(
icon: Icon(
flash ? Icons.flash_on : Icons.flash_off,
color: Colors.white,
size: 28,
),
onPressed: () {
setState(() {
flash = !flash;
});
flash
? _cameraController!
.setFlashMode(FlashMode.torch)
: _cameraController!
.setFlashMode(FlashMode.off);
}),
),
),
ValueListenableBuilder<bool>(
valueListenable: isRecoring,
builder: (context, value, child) {
return GestureDetector(
onLongPress: () {
startRecording();
},
onLongPressUp: () {
stopRecording();
},
onTap: () {
if (value == false) {
takePhoto(context);
}
},
child: value == true
? const CircleAvatar(
radius: 50,
backgroundColor: Colors.white30,
child: CircleAvatar(
radius: 35,
backgroundColor: Colors.red,
),
)
: const CircleAvatar(
radius: 35,
backgroundColor: Colors.white30,
child: CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
),
));
}),
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withOpacity(0.5)),
child: IconButton(
icon: const Icon(
Icons.flip_camera_ios,
color: Colors.white,
size: 28,
),
onPressed: () async {
setState(() {
iscamerafront = !iscamerafront;
});
int cameraPos = iscamerafront ? 0 : 1;
_cameraController = CameraController(
cameras![cameraPos], ResolutionPreset.high);
cameraValue = _cameraController?.initialize();
}),
),
],
),
addVerticalSpace(6),
const Text(
"Hold for Video, tap for photo",
style: TextStyle(
color: Colors.white,
),
textAlign: TextAlign.center,
),
addVerticalSpace(5),
],
),
),
),
],
),
),
);
}
void startRecording() async {
visible.value = true;
_timerProvider?.startCountDown(_maxSeconds);
isRecoring.value = true;
await _cameraController?.startVideoRecording();
}
void stopRecording() async {
XFile videopath = await _cameraController!.stopVideoRecording();
_timerProvider?.stopTimer();
isRecoring.value = false;
Navigator.push(
context,
MaterialPageRoute(
builder: (builder) => CameraResult(
image: File(videopath.path),
isImage: false,
))).then((value) {
visible.value = false;
});
}
void takePhoto(BuildContext context) async {
XFile file = await _cameraController!.takePicture();
SystemSound.play(SystemSoundType.click);
final img.Image? capturedImage =
img.decodeImage(await File(file.path).readAsBytes());
final img.Image orientedImage = img.flipHorizontal(capturedImage!);
File finalImage =
await File(file.path).writeAsBytes(img.encodeJpg(orientedImage));
Navigator.push(
context,
CupertinoPageRoute(
builder: (builder) => CameraResult(
image: finalImage,
isImage: true,
))).then((value) {
visible.value = false;
});
}
}
the upload function is as bellow
{File? shouts,
File? thumbnail,
int? duration,
bool? isImage,
required String userId,
required OnUploadProgressCallback onUploadProgress}) async {
assert(shouts != null);
try {
var url = Constants.POSTSHOUTURL;
final httpClient = FileService.getHttpClient();
final request = await httpClient.postUrl(Uri.parse(url));
int byteCount = 0;
var multipart;
if (isImage == false) {
multipart = await http.MultipartFile.fromPath(
'story-media', shouts!.path,
contentType: MediaType("video", "mp4"));
} else {
multipart = await http.MultipartFile.fromPath(
'story-media',
shouts!.path,
);
}
var multipart2 =
await http.MultipartFile.fromPath('thumbnail', thumbnail!.path);
var requestMultipart = http.MultipartRequest('POST', Uri.parse(url));
requestMultipart.fields["userid"] = userId.toString();
requestMultipart.fields["duration"] = duration.toString();
requestMultipart.headers['Content-type'] = 'multipart/form-data';
requestMultipart.files.add(multipart);
requestMultipart.files.add(multipart2);
var msStream = requestMultipart.finalize();
var totalByteLength = requestMultipart.contentLength;
request.contentLength = totalByteLength;
request.headers.add(HttpHeaders.authorizationHeader,
"Bearer ${Hive.box<UserData>(Constants.userDb).get(Hive.box<UserData>(Constants.userDb).keyAt(0))!.token}");
request.headers.set(HttpHeaders.contentTypeHeader,
requestMultipart.headers[HttpHeaders.contentTypeHeader]!);
Stream<List<int>> streamUpload = msStream.transform(
StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data);
byteCount += data.length;
if (onUploadProgress != null) {
onUploadProgress(byteCount, totalByteLength);
// CALL STATUS CALLBACK;
}
},
handleError: (error, stack, sink) {
throw error;
},
handleDone: (sink) {
sink.close();
// UPLOAD DONE;
},
),
);
await request.addStream(streamUpload);
final httpResponse = await request.close();
var statusCode = httpResponse.statusCode;
if (statusCode ~/ 100 == 2) {
onUploadProgress(0, 0);
return await FileService.readResponseAsString(httpResponse);
}
return "";
} on SocketException {
throw FetchDataException("No internet to upload Shout!");
}
}```
i have used necessary info.plist setting also

flutter:: RangeError (index): Invalid value: Not in inclusive range 0..14: 15

I made a function to delete saved recording files.
The delete function works fine.
However, if it is deleted, an error
'RangeError (index): Invalid value: Not in inclusive range 0..14: 15'
will occur and it will look like the picture above.
How can I solve this?
This is the delete function.
_delete() {
widget.file[widget.index].delete(recursive: true);
setState(() {
position = new Duration();
widget.file.removeAt(widget.index);
});
}
This is my listview code.
class _AudioViewerState extends State<AudioViewer> {
var audioPath;
var directory;
List file = [];
#override
void initState() {
super.initState();
getFiles();
}
void getFiles() async {
directory = (await getExternalStorageDirectory())!.path;
setState(() {
file = Directory("$directory").listSync();
});
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
elevation: 0,
title: Text(
"Audio List",
),
),
body: Container(
child: CustomPaint(
child: ListView.builder(
reverse: true,
itemCount: file.length,
itemBuilder: (BuildContext context, int index) {
return AudioViewerCustomTile(
text: file[index].path.split('/').last,
path: file[index].path.toString(),
height: height,
width: width,
file: file,
index: index,
);
},
),
),
),
);
}
}
This is the file with the delete function.
class DialogBuilder extends StatefulWidget {
final String path;
final int index;
final List file;
DialogBuilder({required this.path,required this.index,required this.file});
#override
_DialogBuilderState createState() => _DialogBuilderState();
}
class _DialogBuilderState extends State<DialogBuilder> {
late AudioPlayer audioPlayer;
bool _isplaying = false;
var _icon = Icons.play_arrow;
var _deleteicon = Icons.delete;
Color _color = Colors.deepOrangeAccent;
Duration position = Duration();
Duration duration = Duration(seconds: 1);
#override
Widget build(BuildContext context) {
return Container(
height: 200,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: <Widget>[
Container(
child: Row(
children: <Widget>[
Container(
child: IconButton(
iconSize: 100,
onPressed: () {
if (!_isplaying) {
_play();
} else {
_stop();
}
},
icon: Icon(_icon),
color: _color,
),
),
Container(
child: IconButton(
iconSize: 50,
onPressed: () {
_delete();
},
icon: Icon(_deleteicon),
),
),
]
)
),
Padding(
padding: const EdgeInsets.all(8.0),
child: LinearProgressIndicator(
backgroundColor: Colors.grey[300],
valueColor: AlwaysStoppedAnimation(Colors.deepOrangeAccent),
value: (position.inMilliseconds / duration.inMilliseconds) * 1.0,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
_getDuration(position),
style: TextStyle(color: Colors.black),
),
Text(
_getDuration(duration),
style: TextStyle(color: Colors.black),
)
],
),
)
],
),
);
}
String _getDuration(Duration duration) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
_play() {
audioPlayer.resume();
setState(() {
_isplaying = true;
_icon = Icons.pause;
_color = Colors.blueGrey;
});
}
_stop() {
audioPlayer.release();
setState(() {
position = new Duration();
_isplaying = false;
_icon = Icons.play_arrow;
_color = Colors.deepOrangeAccent;
});
}
_delete() {
widget.file[widget.index].delete(recursive: true);
setState(() {
position = new Duration();
widget.file.removeAt(widget.index);
});
}
_stateListener(PlayerState state) {
print(" In _stateListener the state of AudioPlayer :- " +
state.toString() +
"\n");
if (state == PlayerState.COMPLETED) {
Navigator.pop(context);
_stop();
}
}
The List file = []; is an empty list, so when you try to do itemCount = file.length, it displays an error, try giving the List file; a value instead of a an empty list and im sure it will work