如何在Flutter中完成数据加载后呈现我的小部件

问题描述 投票:0回答:1

我想做什么登录后,显示具有列表视图的HomeScreen。此列表视图显示了来自API的数据。因此,加载需要一点时间。我想在加载完成后渲染主屏幕,并且列表视图中充满了数据。

我已经完成的事情我有一个做api的api帮助器类。它有一个静态方法,该方法正在获取我的listview的数据并返回一个列表。这是我的getFixtureData方法。

 static Future<List<Fixtures>> getFixtureData() async {
    Map<String, String> queryParameters = {
      'league': '78',
      'next': '20',
    };

    http.Response response = await http.get(
      getUrl('fixtures', queryParameters),
      headers: requestHeaders,
    );

    print(response.body);

    if (response.statusCode == 200) {
      String data = response.body;
      List<dynamic> result = jsonDecode(data)['response'];

      for (int i = 0; i < result.length; i++) {
        Fixtures fixture = Fixtures();

        fixture.leagueID = jsonDecode(data)['response'][i]['league']['id'];
        fixture.country = jsonDecode(data)['response'][i]['league']['country'];
        fixture.leagueName = jsonDecode(data)['response'][i]['league']['name'];
        fixture.fixtureID = jsonDecode(data)['response'][i]['fixture']['id'];

        //get Odds to match with fixtures by fixtureID
        await getOddsData(fixture.fixtureID);

        fixture.dateTime =
            DateTime.parse(jsonDecode(data)['response'][i]['fixture']['date']);
        fixture.homeTeam =
            jsonDecode(data)['response'][i]['teams']['home']['name'];
        fixture.awayTeam =
            jsonDecode(data)['response'][i]['teams']['away']['name'];
        fixture.status =
            jsonDecode(data)['response'][i]['fixture']['status']['long'];
        fixture.homeGoals = jsonDecode(data)['response'][i]['goals']['home'];
        fixture.awayGoals = jsonDecode(data)['response'][i]['goals']['away'];
        fixture.htScoreHome =
            jsonDecode(data)['response'][i]['score']['halftime']['home'];
        fixture.htScoreAway =
            jsonDecode(data)['response'][i]['score']['halftime']['away'];
        fixture.ftScoreHome =
            jsonDecode(data)['response'][i]['score']['fulltime']['home'];
        fixture.ftScoreAway =
            jsonDecode(data)['response'][i]['score']['fulltime']['away'];

        if (oddsList.length > 0) {
          for (int j = 0; j < oddsList.length; j++) {
            if (oddsList[j].fixtureID == fixture.fixtureID) {
              fixture.homeOdds = oddsList[j].homeOdds;
              fixture.drawOdds = oddsList[j].drawOdds;
              fixture.awayOdds = oddsList[j].awayOdds;
              fixture.bookmakerName = oddsList[j].bookmakerName;
              FootballApi.fixtureList.add(
                  fixture); // this line must be here. If there is no odds of that match, it should not be in fixtureList
            }
          }
        }
      }
    } else {
      print('statusCode: ' + response.statusCode.toString());
    }

    return FootballApi.fixtureList;
  }

我在有状态的小部件(HomeScreen)中调用此方法,该小部件具有一个列表视图,我将其与返回的列表getFixtureData方法一起提供给它。我在HomeScreen的initState中调用它。这是相关的代码。

class HomeScreen extends StatefulWidget {
  static String id = 'home_screen';

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int gameIndex = 0;
  String gameTitle = 'Soccer';
  int selectedCategoryIndex = 0;
  List<Fixtures> fixtureList = List<Fixtures>();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getFixture();
  }

  Future<List<Fixtures>> getFixture() async {
    fixtureList = await FootballApi.getFixtureData();
    return fixtureList;
  }

这是我将数据传递到HomeScreen中的listview的位置。

      Stack(children: [
        AppListView(
          matchList: FootballApi.fixtureList,
          //callback function brings the matchCounter value from ListView class
          onChange: (value) {
            setState(() {
              matchCounter = value;
            });
          },
          finalBetList: (value) {
            setState(() {
              betList = value;
            });
          },
        ),

问题是;用户登录时,他正在用空白列表视图查看我的主屏幕。几秒钟后,将加载listview。我想在列表视图完全加载后呈现HomeScreen。最好的方法是什么?

flutter asynchronous dart future
1个回答
0
投票

从异步函数获取数据后,使用FutureBuilder小部件来构建小部件;

FutureBuilder<List<Fixtures>>(
  future: getFixture(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      List<Fixtures> yourResponseDataFromAsync = snapshot.data;
      return AppListView(
        matchList: yourResponseDataFromAsync,
        //callback function brings the matchCounter value from ListView class
        onChange: (value) {
          setState(() {
            matchCounter = value;
          });
        },
        finalBetList: (value) {
          setState(() {
            betList = value;
          });
        },
      );
    }
    return CircularProgressIndicator();
  },
),
© www.soinside.com 2019 - 2024. All rights reserved.