I am trying to integrate pagination with gridview.builder,it's working in listview without any problem but in gridview it doesn't work as expected,The problem i am facing is The API data is returns 20 data per page,
Problem:In API it returns 20 data/page,in this API it returns total of 21 data,in 1 st page contains 20 data 2nd page contains only 1 data the pagination is working i can load data but i cannot scroll back to page 1 data it just stuck with page 2 data
I am following this Tutorial,this is working with listview without no problem but in gridview the above problem occurs
InitState and Variable initialization
var page = 1;
ScrollController _sccontroller = new ScrollController();
#override
void initState() {
super.initState();
Future token = SharedPrefrence().getToken();
token.then((data) async {
userToken = data;
this.getSearchResult(page);
_sccontroller.addListener(() {
if (_sccontroller.position.pixels ==
_sccontroller.position.maxScrollExtent) {
getSearchResult(page);
}
});
});
setState(() {
title = name;
});
}
#override
void dispose() {
_sccontroller.dispose();
super.dispose();
}
Gridview
GridView.builder(
controller: _sccontroller,
itemCount: search_result_list.length + 1,
physics: const AlwaysScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(childAspectRatio: 5.2 / 8.0,
crossAxisCount: 2, crossAxisSpacing: 3.0, mainAxisSpacing: 3.0),
itemBuilder: (BuildContext context, int index) {
if (index == search_result_list.length) {
return Center(child: Padding(padding: const EdgeInsets.all(8.0), child: CircularProgressIndicator(),));
} else {
return Container(
child: Padding(
padding: const EdgeInsets.only(top:10),
child: GestureDetector(
onTap: () {
},
child: Container(
// height: 700,
child: Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(2),
),
child: Container(
width: 300,
//height: 500,
child: Stack(
children: [
Column(
mainAxisSize: MainAxisSize.min,
//crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.all(2),
child: Image.network(
Urls.baseImageUrl +
search_result_list[index]
.thumb_path,
fit: BoxFit.fill,
height: 180,
width: 180,
),
),
Padding(
padding: const EdgeInsets.all(5),
child: Align(
child: Text(
search_result_list[index].name,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold),
textAlign: TextAlign.left,
),
alignment: Alignment.centerLeft,
)),
],
),
],
)),
),
),
),
),
);
}
},
)
API Function
Future<void> getSearchResult(int index) async {
print("size" + index.toString());
if (!isLoading) {
setState(() {
isLoading = true;
});
// ProgressDialog dialog = CustomDialogs().showLoadingProgressDialog(context);
List<PrefrenceModel> tList = List();
var response = await http.get(
"${Urls.baseUrl}${Urls.CategorySearch}?latitude=${Constants
.latitude}&longitude=${Constants
.longitude}&radius=100&locale=en&keyword=${slug}&page=${index
.toString()}&type=item",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer ${userToken}",
"Accept": "application/json"
},
);
Map<String, dynamic> value = json.decode(response.body);
if (response.statusCode == 200) {
// dialog.dismissProgressDialog(context);
try {
print("response search " + response.body.toString());
Map<String, dynamic> value = json.decode(response.body);
var status = value['success'];
var message = value['message'];
last_page = value['last_page'];
print(message);
if (status == true) {
search_result_list.clear();
try {
var data = value['data']['data'];
if (data.length > 0) {
for (int i = 0; i < data.length; i++) {
var obj = data[i];
//var petrol_obj = obj['petrolstation'];
search_result_list.add(PrefrenceModel(
obj['id'].toString(),
obj['description'].toString(),
obj['valid_from'].toString(),
obj['valid_to'].toString(),
obj['thumbs']['md'].toString(),
obj['status'].toString(),
"",
"",
obj['name'].toString(),
"",
obj['flyer_slug'].toString(),
obj['type'].toString(),
obj['isClipped'],
obj['url'].toString(),
obj['price'].toString(),
obj['flyer_page_id'].toString(),
obj['id'].toString(),
obj['shop_name'].toString(),
obj['shop_logo'].toString(),
obj['brand_name'].toString(),
obj['brand_logo'].toString(),
));
}
setState(() {
isLoading = false;
search_result_list.addAll(tList);
page++;
});
} else {
final snackBar = SnackBar(content: Text("No Data Available"));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
e.toString();
}
} else {
print("Error...");
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
} catch (e) {
print(e.toString());
}
} else {
var message = value['message'];
// dialog.dismissProgressDialog(context);
final snackBar = SnackBar(content: Text(message));
_scaffoldKey.currentState.showSnackBar(snackBar);
}
}
else
{
setState(() { isLoading = false; });
}
}
Pagination will gives you the data related to the page, for example page one will returns data from 1 to 20, page two from 21 to 40. so you have to add data of page 2 to existed data from page 1. but in your case you are calling search_result_list.clear(); this will erase the old data and put only the new data into the list.
Related
I am trying to build a list from http server, and would like to implement page load for large data set. I tried with lazy_load_scrollview package and follow the example, I can load additional records from the server on End of page, but when new records are loaded, the list jumps up to the first record. How could I avoid this?
int totalRecords = 0;
int recordsPerPage = 5;
int currentPage = 1;
int totalPages = 1;
List<dataRecord> dataList = [];
List<dataRecord> fullList = [];
bool isLoading = false;
//class definitions...
class searchClient extends StatefulWidget {
#override
_searchClientState createState() => _searchClientState();
}
class _searchClientState extends State<searchClient> {
final _searchItemController = TextEditingController();
#override
void initState() {
super.initState();
dataList = [];
currentPage = 1;
}
List<dataRecord> parseJson(String responseBody) {
final parsed =
convert.jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<dataRecord>((json) => dataRecord.fromJson(json)).toList();
}
#override
void dispose() {
_searchItemController.dispose();
super.dispose();
}
void loadData() async {
setState(() {
isLoading = true;
});
if (totalRecords == 0) {
final response2 = await http.get(
Uri.parse('http://192.168.0.8:88/searchcustomer_gettotal' +
'?userID=' +
globals.userID.toString() +
'&token=' +
globals.token +
'&name=' +
_searchItemController.text),
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Connection": "Keep-Alive",
},
);
Map<String, dynamic> totalMap = convert.jsonDecode(response2.body);
var total = totals.fromJson(totalMap);
totalRecords = total.total;
var t = totalRecords / recordsPerPage;
if (totalRecords < recordsPerPage) {
totalPages = 1;
}else if (totalRecords%recordsPerPage == 0) {
totalPages = t.round();
}else{
var t = totalRecords / recordsPerPage;
totalPages = t.round()+ 1;
}
print(totalRecords);
}
;
final response = await http.get(
Uri.parse('http://192.168.0.8:88/searchcustomer' +
'?userID=' +
globals.userID.toString() +
'&token=' +
globals.token +
'&name=' +
_searchItemController.text +
'&pageno=' +
currentPage.toString() +
'&perpage=' +
recordsPerPage.toString()),
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Connection": "Keep-Alive",
},
);
setState(() {
isLoading = false;
});
dataList = parseJson(response.body);
fullList = List.from(fullList)..addAll(dataList);
}
void loadMore() {
if (currentPage < totalPages) {
currentPage += 1;
loadData();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Search Client')),
body: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 20),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(), labelText: 'Search Item'),
controller: _searchItemController,
),
),
Container(
height: 45,
width: 250,
decoration: BoxDecoration(
color: Colors.teal, borderRadius: BorderRadius.circular(16)),
child: TextButton(
onPressed: () {
totalRecords = 0;
fullList = [];
loadData();
},
child: Text(
'Search',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
SizedBox(height: 20),
isLoading
? Center(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: CircularProgressIndicator(),
),
)
: Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 0),
child: LazyLoadScrollView(
isLoading: isLoading,
onEndOfPage: () {
loadMore();
},
child: ListView.builder(
itemCount: fullList.length,
itemBuilder: (BuildContext context, int index) {
return dataCard(context, fullList, index);
}),
),
),
),
],
),
);
}
}
Could you try removing this widget of your tree
Center(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: CircularProgressIndicator(),
),
)
in order to only have your Scrollview ?
My guess is that since you're calling the setState method at load time, your whole widget tree is rebuilt, and when your new datas are fetched the whole listview is rebuilt, losing the previous position.
I'll edit my answer with some code if this doesn't fix your problem
I am facing an issue when I pull to refresh, I need that after pull to refresh gesture new articles available will be visible in the news page, but this doesn't happen.
I created the cache system, but once I pull to refresh new data, the news page doesn't load new articles.
What can I do to solve this issue?
News page
class _NewsPageState extends State<NewsPage> {
/// News service
final ApiNewsPage categoryNews = ApiNewsPage();
late bool isLoading;
/// Start Refresh indicator upload new articles function
final NewArticlesPage updateArticles = NewArticlesPage();
ScrollController scrollController = ScrollController();
//final List<ArticleModel> _posts = [];
//
#override
void initState() {
super.initState();
refreshArticles();
}
/// Call this when the user pull down the screen
Future<void> refreshArticles() async {
Future.delayed(const Duration(seconds: 2), () {
setState(() {
updateArticles.updateArticles();
print("Uploading new articles");
//_posts.add();
});
return updateArticles.updateArticles();
});
}
/// End Refresh indicator upload new articles function
///
///
#override
Widget build(BuildContext context) {
return RefreshIndicator(
displacement: 0,
color: assofacileMainColor,
backgroundColor: Colors.white,
onRefresh: refreshArticles,
child: Container(
child: FutureBuilder<List?>(
future: categoryNews.getNewsArticles(),
builder: (context, snapshot) { // AsyncSnapshot
if (snapshot.hasData) {
if (snapshot.data?.length == 0) {
return const NoArticle();
}
return ListView.builder(
controller: scrollController,
itemCount: snapshot.data?.length++,
physics: const AlwaysScrollableScrollPhysics(),
itemBuilder: (context, i) {
return Card(
margin: const EdgeInsets.all(8),
elevation: 5,
shadowColor: Colors.black26,
color: Colors.white,
child: InkWell(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 190,
width: double.infinity,
child:
Image(
image: AdvancedNetworkImage(
snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
useDiskCache: true,
cacheRule: const CacheRule(maxAge: Duration(days: 1)),
),
fit: BoxFit.cover,
),
// CachedNetworkImage(
// cacheManager: CacheManager(
// Config(snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
// stalePeriod: const Duration(days: 1),
// )
// ),
// //cacheManager: DioCacheManager.instance,
// imageUrl: snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
// // checkIfUrlContainsPrefixHttps(
// // _post != null
// // ? _post[0].urlImageSource
// // : "https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["thumbnail"]["source_url"],
// // ),
// //snapshot.data![i]["_embedded"]["wp:featuredmedia"][0]["link"],
// //"https:" + snapshot.data![i]["_embedded"]['wp:featuredmedia'][0]["media_details"]["sizes"]["medium"]["source_url"],
// fit: BoxFit.cover,
// placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif",
// width: double.infinity,
// height: 190,
// fit: BoxFit.cover,
// ),
// errorWidget: (context, url, error) => Image.asset("assets/images/unloadedImage.png",
// width: 250, height: 250),
// ),
),
// Title article
Column(
children: [
Padding(
padding: const EdgeInsets.only(left:16, top: 16, bottom: 16),
child: Row(
children: [
Expanded(
child: Text(
snapshot.data![i]["title"]["rendered"]
.replaceAll("’", "'")
.replaceAll("<p>", "")
.replaceAll("</p>", ""),
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
fontFamily: "Raleway",
),
overflow: TextOverflow.ellipsis,
maxLines: 2,
//softWrap: false,
),
),
],
),
)
],
),
],
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(data: snapshot.data?[i]),
),
);
},
),
);
},
);
} else if (snapshot.hasError) {
return const NoInternet();
} else {
/// Shimmer
return ShimmerEffect();
}
}
),
),
);
}
}
Fetch and create cache
class ApiNewsPage {
final String url = newsJsonLink;
Future<List?> getNewsArticles() async {
String nameDB = "articledata.json";
var dir = await getTemporaryDirectory();
File file = File(dir.path + "/" + nameDB);
if(file.existsSync()) {
print("Loading Articles from cache");
var jsonDB = file.readAsStringSync();
List response = json.decode(jsonDB);
return response;
} else {
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
//await File(nameDB).exists();
var jsonResponse = response.body;
List newArticles = json.decode(jsonResponse);
//File(nameDB).deleteSync(recursive: true);
/// save json in local file
file.writeAsStringSync(jsonResponse, flush: true, mode: FileMode.write);
print("Fetching new articles from internet");
return newArticles;
}
}
}
}
// Create new db
class NewArticlesPage {
final String url = newsJsonLink;
Future<List?> updateArticles() async {
try {
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
print("Fetching new articles from internet");
return jsonDecode(response.body);
} else {
return Future.error("Impossibile ricevere i dati, prova a controllare la connessione");
}// ignore: non_constant_identifier_names
} catch (SocketException) {
return Future.error("Impossibile caricare gli articoli");
}
}
}
Faced a problem. I started to paginate the list so that 10 elements are displayed, when I reach the bottom of the list using controller.position.extentAfter < 30 I check how far we have gone down and if at the very bottom I change the value of isLoadMoreRunning and show CircularProgressIndicator. I will also add +10 elements to the limit variable for each call to display. I seem to have done everything right, but pagination does not work for me, it shows the first 10 elements, and then nothing passes, new elements are not loaded when I scrolled to the very bottom. What could be the problem?
home
late ScrollController controller;
bool isFirstLoadRunning = false;
bool isLoadMoreRunning = false;
bool hasNextStation = true;
int limit = 10;
void _firstLoadStations() async {
final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);
setState(() {
isFirstLoadRunning = true;
});
try {
stationsList =
await stationCubit.getAllPublicChargingStations(limit: limit);
} catch (error) {
print(error);
}
setState(() {
isFirstLoadRunning = false;
});
}
void _loadMoreStations() async {
final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);
if (hasNextStation == true &&
isFirstLoadRunning == false &&
controller.position.extentAfter < 30) {
setState(() {
isLoadMoreRunning = true;
});
limit += 10;
try {
var fetchedStations =
await stationCubit.getAllPublicChargingStations(limit: limit);
if (fetchedStations.isNotEmpty) {
setState(() {
stationsList.addAll(fetchedStations);
});
} else {
setState(() {
hasNextStation = false;
});
}
} catch (error) {
print(error);
}
setState(() {
isLoadMoreRunning = false;
});
}
// _foundAddressesInStationList = stationsList;
}
#override
void initState() {
_firstLoadStations();
controller = ScrollController()
..addListener(() {
_loadMoreStations();
});
_foundAddresses = _allAddresses;
_foundStation = _allStation;
super.initState();
}
#override
void dispose() {
controller.removeListener(() {
_loadMoreStations();
});
super.dispose();
}
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double paddingTop = MediaQuery.of(context).padding.top;
final StationCubit stationCubit = BlocProvider.of<StationCubit>(context);
return Container(
width: size.width,
height: size.height,
child: _child(size, paddingTop, stationCubit),
);
}
Widget _child(Size size, double paddingTop, StationCubit stationCubit) =>
BlocBuilder<StationCubit, StationState>(
builder: (context, state) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
children: [
const SizedBox(height: 17),
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
_addresses(size, stationCubit),
],
),
),
),
],
),
),
);
Widget _addresses(Size size, StationCubit stationCubit) => ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height / 2,
),
child: SizedBox(
width: size.width,
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
child: Container(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
isFirstLoadRunning
? const CircularProgressIndicator(
color: Colors.white)
: const Text(
'Addresses',
style: constants.Styles.smallBookTextStyleWhite,
),
const SizedBox(height: 25),
ListViewSearch(
stationList: stationsList,
controller: controller,
),
const SizedBox(height: 20),
if (isLoadMoreRunning == true)
const Padding(
padding: EdgeInsets.only(top: 10, bottom: 40),
child: Center(
child: CircularProgressIndicator(),
),
),
if (hasNextStation == false)
Container(
padding: const EdgeInsets.only(top: 30, bottom: 40),
color: Colors.amber,
child: const Center(
child:
Text('You have fetched all of the content'),
),
),
],
),
)),
),
),
),
);
}
cubit
Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
{required int limit}) async {
var result =
await StationRepository().getAllPublicChargingStations(limit: limit);
return result;
}
repository
Future<List<PublicChargingStationModel>> getAllPublicChargingStations(
{int? limit}) async {
try {
var apiKeyMap = await ApiKey.getCryptoApiKeyMap();
apiKeyMap!.addAll({'limit': limit.toString()});
final Uri url = Uri.parse(
'${ApiConfig.schema}://${ApiConfig.domain}/${ApiConfig.uriPrefix}/stations',
).replace(queryParameters: apiKeyMap);
final response = await http.get(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body)['data'] as List;
return data
.map((json) => PublicChargingStationModel.fromJson(json))
.toList();
}
return List<PublicChargingStationModel>.empty();
} catch (_) {
print(_);
return List<PublicChargingStationModel>.empty();
}
}
you need set SingleChildScrollView parameter controller: controller.
I need help in this please i have a RefreshIndicator that loads a ListView when there is data in the database however I want to make the widget return Text widget 'no data' if the table empty instead of the ListView.
but the when the table is empty it error appear
_TypeError (type 'String' is not a subtype of type 'Iterable')
and that will appear in the refresh method i don't know what should i do i appreciate any help thanks in advance.
this the UI for the page
class _onlineResultTab extends State<onlineResultTab> {
List<ResultsModelClass> resultslist = new List();
List<CoursesModelClass> coursesist = new List();
ResultsModelClass resultsModelClass;
CoursesModelClass courseModelClass;
final GlobalKey<RefreshIndicatorState> refreshKey = GlobalKey<RefreshIndicatorState>();
DataApiProvider dataApiProvider = new DataApiProvider();
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
key: refreshKey,
onRefresh: refreshList,
child: _resultwidget(context),
),
);
}
fetchResultDetails() async {
final allRows = await DbHelper.mydb.getOnlineResultList();
allRows.forEach((row) => {
resultsModelClass = ResultsModelClass(
"",
row["Res_Stud_Index"],
row["Res_Stud_Name"],
row["Res_Sem"].toString(),
"",
"",
row["Res_Batch"],
row["Res_Courses"],
row["Res_Grade"],
row["Res_GPA"].toString(),
row["Res_CGPA"],
row["Res_Status"],
row["faculty_desc_e"],
row["major_desc_e"]),
resultslist.add(resultsModelClass)
});
if (this.mounted) {
setState(() {});
}
}
fetchCourse() async {
final allRows = await DbHelper.mydb.getResultcoursesList();
allRows.forEach((row) => {
courseModelClass = CoursesModelClass(
row["Res_Courses"],
row["Res_Grade"],
),
coursesist.add(courseModelClass)
});
if (this.mounted) {
setState(() {});
}
}
List<String> listHeader = ['Student Results Details'];
Widget _resultwidget(context) {
final _size = MediaQuery.of(context).size;
return resultslist.length == 0
? ListView.builder(
controller: ScrollController(),
itemCount: 1,
itemBuilder: (context, index) {
return Center(
child: Padding(
padding: EdgeInsets.only(top: _size.height * 0.4),
child: Text(
"No Result Details !",
style: TextStyle(fontSize: 20),
),
));
},
physics: AlwaysScrollableScrollPhysics(),
)
: new ListView.builder(
itemCount: listHeader.length,
itemBuilder: (context, index) {
//var _size = MediaQuery.of(context).size;
return SingleChildScrollView(
child: Center(
child: Padding(
padding: EdgeInsets.only(bottom: _size.height * 0.02),
child: Column(
children: [
Card(
elevation: 20,
margin: EdgeInsets.symmetric(
horizontal: _size.width * 0.005,
),
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor),
child: Center(
child: Text(
'Semester ' +
resultslist[0].Res_Sem +
' Result ',
style: TextStyle(
color: Colors.white,
fontSize: 17,
fontWeight: FontWeight.bold),
),
),
),
),
],
))),
);
},
);
}
the refresh method
Future<String> refreshList() async {
refreshKey.currentState?.show(atTop: false);
//await Future.delayed(Duration(seconds: 10));
var studentIndex;
final allRows = await DbHelper.mydb.MainInfoCehck();
allRows.forEach((row) => {
row["Stud_Index"],
studentIndex = row["Stud_Index"].toString()
//print( row["Stud_Index"].toString())
});
print(studentIndex);
//void refreshResult(String studentIndex)async{
await dataApiProvider.refresh_result(studentIndex);
// }
if (this.mounted) {
setState(() {
coursesist.clear();
resultslist.clear();
fetchResultDetails();
fetchCourse();
});
}
return null;
}
Future<String> refresh_result(String studentIndex) async {
var url = main_urll + "?studentIndex=" + studentIndex.trim();
final response = await http.get(url);
List<ResultDetailsModel> ResulttDetailsListModel = [];
final resultInfo = jsonDecode(response.body)['result_info'];
DbHelper.mydb.deleteTableData("Result");
print('Result informations : ' + resultInfo.toString());
for (Map i in resultInfo) {
ResulttDetailsListModel.add(ResultDetailsModel.fromJson(i));
DbHelper.mydb.saveResultDetails(ResultDetailsModel.fromJson(i));
}
return "";
}
Please check if
resultslist == null or resultslist.isNotEmpty()
for Handling empty list
I have tried with pageToken, but the problem is when first 50 elements are added into videos list, after that next 50 are not adding.After showing first 50 data and when it should get next 50, it is showing the error:
RangeError (index): Invalid value: Not in range 0..28, inclusive: 50
I will be very grateful if I get the solution, Thanks in advance.
class _PlaylistPageState extends State<PlaylistPage> {
bool isMore = false;
Map data = new Map();
List<dynamic> videos = new List();
getData() async {
String baseUrl =
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${widget.plist}" +
"&maxResults=50&key=" +
"AIzaSyCrrzqrXMfI8xpD0a5wdU1xDcc7QTUjLSA";
String nextPageUrl =
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${widget.plist}" +
"&maxResults=50&pageToken=CDIQAA&key=" +
"AIzaSyCrrzqrXMfI8xpD0a5wdU1xDcc7QTUjLSA";
var baseResponse;
var nextPageResponse;
if(!isMore){
baseResponse = await http.get(baseUrl);
} else {
nextPageResponse = await http.get(nextPageUrl);
}
setState(() {
if(!isMore){
videos.add(json.decode(baseResponse.body)["items"]);
} else {
videos.add(json.decode(nextPageResponse.body)["items"]);
}
});
}
fetchTen(){
for(int i = 0; i < 10; i++){
getData();
}
}
ScrollController _scrollController = new ScrollController();
#override
void initState() {
super.initState();
fetchTen();
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if(videos.length == 50){
setState(() {
isMore = true;
});
}
//print(videos.length);
fetchTen();
}
});
}
#override
void dispose() {
_scrollController.dispose();
super.dispose();
}
}
#override
Widget build(BuildContext context) {
return Center(
child:ListView.builder(
controller: _scrollController,
itemCount: videos == null ? 0 : videos.length,
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Material(
elevation: 8.0,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
child: Column(
children: <Widget>[
Container(
height: 200,
width: 300,
decoration: new BoxDecoration(
image: new DecorationImage(
image: new NetworkImage(videos[index][index]["snippet"]
["thumbnails"]["high"]["url"]),
fit: BoxFit.cover,),
borderRadius: BorderRadius.circular(10)
),
padding: EdgeInsets.all(8.0),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new Center(child: Text(videos[index][index]["snippet"]["title"], textAlign: TextAlign.center,),),
),
],
),
),
);
})
);
}
I expected to have all the video list in the playlist, But I am getting only first 50 perfectly. So, how to get all videos from youtube playlist ?
You can put a while loop which checks if nextPageToken is null or not and if it isn't you continue to fetch it and save in a temporary list. After it has been done you can just save it in your original list.
while (pageToken != null) {
final response = await DataFetcher(
playlistId: playlistId,
pageToken: pageToken)
.FetchVideoFromPlaylist();
final extracted_data = json.decode(response) as Map<String, dynamic>;
pageToken = extracted_data['nextPageToken'];
List<dynamic> data = extracted_data['items'];
data.forEach((item) {
title = item['snippet']['title'];
thumbnail_url = item['snippet']['thumbnails']['high']['url'];
videoid = item['contentDetails']['videoId'];
print(title);
videoDet.add(
new VideoDetails(
videoId: videoid,
videoUrl: null,
video_thumbnail: thumbnail_url,
video_title: title)
);
});
if (id == 1)
cdVideoData = videoDet;}
In this DataFetcher is a function which is used to fetch videos from youtube. And videodet is a temporary list used to store videos until it finishes adding all