实例成员“ PageNumber”无法在初始化程序中访问。尝试使用其他表达式替换对实例成员的引用

时间:2020-09-20 08:09:14

标签: class flutter oop dart

无法在初始化程序中访问实例成员'PageNumber'。尝试使用其他表达式替换对实例成员的引用

我该如何解决?

这是怎么回事

头等舱


    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
          },
        );
      }
    }


第二堂课


    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!";
      }
    }

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您需要更改为此。

        0  1  2 ... 11 12 13 ... 22 23
+12-1: 11 12 13 ... 22 23 24 ... 33 34
 % 12: 11  0  1 ... 10 11  0 ...  9 10
   +1: 12  1  2 ... 11 12  1 ... 10 11 

答案 1 :(得分:0)

在这种情况下,您需要使用FutureBuilder,因为getPosts()asyc方法。

重构代码:

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..');
       }
     )