Reputation: 103
I am calling the following function through initState but for some reason it is not running, when I print some "test" nothing appears on the console. What can be wrong? (There's other functions inside my State)
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home>
with AutomaticKeepAliveClientMixin<Home> {
@override
void initState() {
super.initState();
getInfo();
}
int countPost = 0;
List<Post> contentList = [];
getInfo() async {
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
setState(() {
countPost = querySnapshot.documents.length;
contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
});
print("Test");
}
}
Upvotes: 0
Views: 1225
Reputation: 635
First of all, you shouldn't call setState inside initState, also maybe there is some error from the querySnapshot, make a try-catch block to see what is happening.
getInfo() async {
print("init state is started");
try{
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
setState(() {
countPost = querySnapshot.documents.length;
contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
});}
catch(e){
print('error is $e')
}
print("Test");
}
EDIT: a better implementation is by using FutureBuilder:
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State < Home > with AutomaticKeepAliveClientMixin {
int countPost = 0;
List < Post > contentList = [];
Future getInfo() async {
print("FutureBuilder is started");
try {
QuerySnapshot querySnapshot = await contentReference
.document(_id)
.collection("usersContent")
.getDocuments();
countPost = querySnapshot.documents.length;
return contentList = querySnapshot.documents
.map((documentSnapshot) => Post.fromDocument(documentSnapshot))
.toList();
} catch (e) {
return print('error is $e');
}
}
@override
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context);
return FutureBuilder(
future: getInfo(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
strokeWidth: 6,
valueColor:
AlwaysStoppedAnimation < Color > (Colors.redAccent),
),
);
} else {
return Text('Done', style: TextStyle(color: Colors.black, fontSize: 40), );
}
}
);
}
}
Upvotes: 1