从另一个有状态小部件中的一个有状态小部件获取可变数据。

时间:2020-09-18 14:59:22

标签: flutter dart stateful statefulwidget

从另一个有状态小部件中的一个有状态小部件获取变量数据,它们彼此之间没有关系(它们既不是孩子也不是父母)

我希望能够访问另一个文件中的数组(posts)...您可以在代码中查看注释以获取更多信息

我有这个stateful小部件


    import 'package:flutter/material.dart';
    
    import 'package:saviortv/modules/fetchPosts.dart';
    import 'package:saviortv/ui/BuildPost.dart';
    
    class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      @override
      Widget build(BuildContext context) {
        return ListView.builder(
          itemCount: posts == null ? 0 : posts.length, // <== here posts is undefined because it doesn't exist as I want to get it from the other file (See below)
          itemBuilder: (BuildContext context, int index) {
            return buildPost(context, posts, index); //Building the posts list view
          },
        );
      }
    }

另一个Stateful小部件


class FetchPosts extends StatefulWidget {
  FetchPosts({Key key, this.pageNumber = 1}) : super(key: key);
  final int pageNumber;

  @override
  _FetchPostsState createState() => _FetchPostsState(pageNumber);
}

class _FetchPostsState extends State<FetchPosts> {
  _FetchPostsState(this.pageNumber);
  int pageNumber;
  List<wp.Post> posts = []; //<== I want this to be useable in the other file;

  Future<String> getPosts() async {
    var res = await fetchPosts(pageNumber);
    print(pageNumber);
    setState(() {
      posts = res;
    });
    return "Success!";
  }

  // Get _ when app loads;
  @override
  void initState() {
    super.initState();
    this.getPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

我该如何实现?

0 个答案:

没有答案