Reputation: 1684
The instance member 'PageNumber' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
How can I solve this?
Here is how it happens
The first class
class _HomeState extends State<Home> {
int pageNumber = 1;
Future<String> fetchPosts = FetchPosts(pageNumber).getPosts(); //<== The error happens here(PageNumber)
List<wp.Post> posts = FetchPosts(pageNumber).posts; //<== The error happens here (PageNumber)
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (BuildContext context, int index) {
return buildPost(context, posts, index); //Building the posts list view
},
);
}
}
Second class
import 'package:flutter_wordpress/flutter_wordpress.dart' as wp;
import 'package:saviortv/models/fetchWordPressPosts.dart';
class FetchPosts {
FetchPosts(this.pageNumber);
final int pageNumber;
List<wp.Post> posts = [];
Future<String> getPosts() async {
var res = await fetchPosts(pageNumber);
print(pageNumber);
posts = res;
return "Success!";
}
}
How can I solve this?
Upvotes: 0
Views: 799
Reputation: 1847
You need to use FutureBuilder in this scenario, as getPosts()
is asyc method.
Refactored Code:
class FetchPosts {
FetchPosts(this.pageNumber);
final int pageNumber;
Future<wp.Post> getPosts() async {
List<wp.Post> posts = [];
posts = await fetchPosts(pageNumber);
print(pageNumber);
return posts;
}
}
FutureBuilder(
future: FetchPosts(pageNumber).getPosts(),
builder: (context, snapshot) {
if(snapshot.hasData){
List<wp.Post> posts=snapshot.data;
return ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (BuildContext context, int index) {
return buildPost(context, posts, index); //Building the posts list view
},
);
}
return Text('Error..');
}
)
Upvotes: 0
Reputation: 5423
You need to change to this.
class _HomeState extends State<Home> {
int pageNumber = 1;
Future<String> fetchPosts;
List<wp.Post> posts;
@override
void initState() {
fetchPosts = FetchPosts(pageNumber).getPosts();
posts = FetchPosts(pageNumber).posts;
super.initState();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (BuildContext context, int index) {
return buildPost(context, posts, index); //Building the posts list view
},
);
}
}
Upvotes: 0