Why GridView.builder clear when obtain more data in flutter - flutter

I have my GRidView builder and I have my future and my ScrollController, why my gridView clear when scrollController is equal than mi maxScroll and obtain more information? It's supposed to show all of it, not the latest information.
this is my code
future: _future ,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
List<dynamic> loaded = snapshot.data;
return
Container(
width: double.infinity,
height: _screenSize.height * .8,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: MediaQuery.of(context).size.width /(MediaQuery.of(context).size.height /1.5),),
controller: _controller,
itemCount: loaded.length,
itemBuilder: (context, i){
return _row(context,loaded,i);
},
)
);
}else{
and the constructor
Future<List> _future;
ScrollController _controller = ScrollController(initialScrollOffset: 0.0, keepScrollOffset: true);
_SearchPageState(){
_controller.addListener(() {
if(_controller.position.pixels >= _controller.position.maxScrollExtent-30 ){
setState(() {
_future = videoJuegos.getPaginationPopular();
});
}
});
_future = videoJuegos.getPaginationPopular();
}

Your Gridview.builder is clearing because of this line:
List<dynamic> loaded = snapshot.data;
It will clear the current list and add the new data. You should use initialize your list above the future and then use list.add:
List<dynamic> loaded = [];
future: _future ,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
loaded.add(snapshot.data);
return
Container(
width: double.infinity,
height: _screenSize.height * .8,
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: MediaQuery.of(context).size.width /(MediaQuery.of(context).size.height /1.5),),
controller: _controller,
itemCount: loaded.length,
itemBuilder: (context, i){
return _row(context,loaded,i);
},
)
);
}else{
Hope that helps.

Related

Could not find the correct Provider<AppNotifiers> above this TopCard Widge

Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height / 815;
double width = MediaQuery.of(context).size.width / 375;
var data = Provider.of<AppNotifiers>(context);
return FutureBuilder(
future: data.getFinalData(),
builder: ((BuildContext context, AsyncSnapshot<FinalModel> snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text("Oops! Try again later!"),
);
}
if (snapshot.hasData) {
return ListView.builder(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics()),
itemCount: snapshot.data!.data!.coins!.length,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemBuilder: ((context, index) {
I have encountered an error. The error is Could not find the correct Provider above this.

how to get images from firestore to gridview

am trying to fetch image from firestore to gridview.but to each container where image should be displayed am getting the error.....NoSuchMethodError: '[]',Dynamic call of null,Receiver:instanceof '_jsonQuerySnapshot', argument[0]..
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("Products")
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot snapshot) {
return snapshot.data == null
? const Center(
child: CircularProgressIndicator())
: GridView.builder(
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemBuilder:
(BuildContext context, int index) {
DocumentSnapshot data =
snapshot.data![index];
Map getdoc =
data.data() as Map<String, dynamic>;
return Container(
height: height * 0.3,
width: width * 0.3,
child: Image.network(
getdoc["product_image_url"]
[index]),
);
},
itemCount: snapshot.data!.docs.length,
);
}))
Try this.
child: Image.network(getdoc["product_image_url"]),

Future builder build only after all recursive call finished

my recursive function to get all .jpg files from device
Directory dir = Directory("/storage/emulated/0");
late CameraController controller;
List<String> visited = [];
List<String> files = [];
Future getphotos(olddir) async {
Directory newdir = olddir;
for (var item in newdir.listSync()) {
if (item.runtimeType.toString() == "_Directory" &&
!visited.contains(item.toString()) &&
!item.path.contains(".thumbnail")) {
visited.add(item.toString());
await getphotos(item);
} else {
if (item.path.endsWith(".jpg")) {
files.add(item.path);
}
}
}
my future builder
FutureBuilder<Object>(
future: temp(),
builder: (context, snapshot) {
return GridView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5),
//if file/folder list is grabbed, then show here
itemCount: snapshot.hasData ? files.length : 5,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(3.0),
child: !snapshot.hasData
? Image.asset("assets/images/load.gif")
: Image.file(
File(files[index]),
fit: BoxFit.cover,
filterQuality: FilterQuality.low,
width: 200,
height: 200,
),
);
});
});
problem: my futurebuilder build its child widget only when the above recursive function is finished, screen stuck while its loading all the images path

The getter was called on null

I am trying to display the list of hobbies of the user from firestore and I get the value from there as it gets print in console but not able to display it.
Error:-
The getter 'hobbies' was called on null.
Receiver: null
Tried calling: hobbies
Create account data is model class:-
Future<CreateAccountData> getUser() async {
final User user = auth.currentUser;
return _reference.doc(user.uid).get().then((m) => CreateAccountData.fromDocument(m));
}
getting data this way and it gets print also in console:-
List hobbies;
void initState() {
super.initState();
getUser().then((value) {
if (!mounted) return;
setState(() {
accountData = value;
hobbies = value.hobbies;
print("hobbies"+ hobbies.toString());
});
});
}
Error takes me to the line I commented:-
child:GridView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: accountData.hobbies.length, // Error take me to hobbies.
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 5, crossAxisSpacing: 5,),
itemBuilder: (BuildContext context, int index){
return Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text(accountData.hobbies[index]),
);
}
),
On suggestions updated to this(wrapped in future builder):-
child: FutureBuilder(
future: getUser(),
builder: (context, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
} if(snapshot.data.docs.isEmpty){
return Align(
alignment: FractionalOffset.centerLeft,
child: Text("Add what you love to do.....",textAlign: TextAlign.left,style: TextStyle(fontSize: 17),),
);
}
return GridView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: accountData?.hobbies?.length ?? 0,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 5,
crossAxisSpacing: 5,),
itemBuilder: (BuildContext context,
int index) {
return Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text(accountData.hobbies[index]),
);
}
);
},
),
Now getting NoSuchMethodError error:-
Class 'CreateAccountData' has no instance getter 'docs'.
Receiver: Instance of 'CreateAccountData'
Tried calling: docs
check hobbies is null
itemCount: accountData?.hobbies?.length ?? 0,
In flutter 2.0, we have null safety. We need to check if value is null or not using an ! mark after the variable. I will post the code in a few minutes since Im in school rn
Wrap GridView.builder in a FutureBuilder passing getUser() as the future.
child: FutureBuilder(
future: getUser(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return CircularProgressIndicator();
if (snapshot.hasData)
return GridView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount:
snapshot.data.hobbies.length, // Error take me to hobbies.
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 5,
crossAxisSpacing: 5,
),
itemBuilder: (BuildContext context, int index) {
//DocumentSnapshot interestList = snapshot.data.docs[index]['hobbies'];
return Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text(snapshot.data.hobbies[index]),
);
});
return Text('No data.');
},
),

How to increment a list variable based on item index?

im getting an error: type int is not a subtype of type List<dynamic> of function result on pressing add
final itemcount = [];
Widget buildItem(BuildContext context, DocumentSnapshot document, int index) {
return Container(
child: Flatbutton(
child:Text("add"),
onpressed:(){
itemcount[index]=itemcount[index]+1,
}
)
);
}
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance
.collection('products')
.where('category', isEqualTo: 'ourstore')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Icon(Icons.photo_library),
);
} else {
return snapshot.data.documents.isEmpty
? Center(child: null)
: GridView.builder(
itemBuilder: (context, index) => buildItem(
context,
snapshot.data.documents[index],
index),
itemCount: snapshot.data.documents.length,
physics: NeverScrollableScrollPhysics(),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
// childAspectRatio: 3/4,
crossAxisSpacing: 10,
mainAxisSpacing: 5,
crossAxisCount: 2),
shrinkWrap: true,
scrollDirection: Axis.vertical,
);
}
},
),
fixed the error
had to set the value to zero for every item in the list
code below:
List<int> itemcount = List<int>();
Widget buildItem(
BuildContext context, DocumentSnapshot document, int index) {
itemcount.add(0);
return Container(
child: Flatbutton(
child:Text("add"),
onpressed:(){
setState(() {
itemcount[index]++;
});
}
)
);
}