Future.then 在构建方法之后运行

Future.then runs after build method

我正在尝试将 AnimatedList 应用到我自己的项目中,它现在运行良好。我想问的是如何future.then 运行s after build method。让我解释一下;

我有一个从另一个小部件调用的小部件。我不明白的部分是 init 方法。小部件获取一个列表,然后每一行在它们之间的指定时间滑动动画。行动画之间有 100 毫秒。到目前为止,一切都很好。但是在 init 方法中循环列表并在最后一个未来之上创建未来。当我在 init 方法中调试或在 for 循环之后放置一些睡眠方法时(你可以看到下面的代码,你可以只关注 init 和 build 方法,其余的不重要),futures 运行 在 build 方法之后。它工作得很好 :) 但我不明白这里的逻辑。

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:guess_score/enum/match_status_enum.dart';
import 'package:guess_score/model/match.dart';
import 'package:guess_score/model/team.dart';
import 'package:guess_score/utility/utility.dart';

class CustomAnimatedList extends StatefulWidget {
  final List<Match> animatedList;
  final Map teamMap;

  CustomAnimatedList({this.animatedList, this.teamMap});

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

class _CustomAnimatedListState extends State<CustomAnimatedList> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();
  List<Match> list = <Match>[];

  @override
  void initState() {
    init();
    super.initState();
  }

  init() {
    print("init");
    var future = Future(() {});
    for (var i = 0; i < widget.animatedList.length; i++) {
      print("init for i =" + i.toString());
      future = future.then((_) {
        print("init for i =" + i.toString() + " - future.then");
        return Future.delayed(Duration(milliseconds: 100), () {
          print("init for i =" + i.toString() + " - future.delayed");
          list.add(widget.animatedList[i]);
          _listKey.currentState.insertItem(list.length - 1);
        });
      });
    }
    sleep(Duration(seconds: 5));
    print("init for ended");
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedList(
      key: _listKey,
      initialItemCount: list.length,
      itemBuilder: (context, index, animation) {
        print("Build itemBuilder");
        return Padding(
          padding: EdgeInsets.all(15.0),
          child: SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(-1, 0),
                end: Offset(0, 0),
              ).animate(animation),
              child: matchRow(list[index])),
        );
      },
    );
  }

  Widget matchRow(Match match) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            teamStat(match.competitionId, match.homeTeam),
            teamLogo(match.competitionId, match.homeTeam),
            SizedBox(
              width: 10,
            ),
            scoreStat(match),
            SizedBox(
              width: 10,
            ),
            teamLogo(match.competitionId, match.awayTeam),
            teamStat(match.competitionId, match.awayTeam)
          ],
        ),
        Text(matchStatusFromString(match.status).getEnumValueAsStringDesc())
      ],
    );
  }

  Widget teamStat(int league, Team team) {
    return Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Column(
            children: [
              Text(
                widget.teamMap[league][team.id].shortName,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget scoreStat(Match match) {
    String home = Utility.getValue(match.score.homeTeamScore);
    String away = Utility.getValue(match.score.awayTeamScore);
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          "$home - $away",
          style: TextStyle(fontSize: 18),
        )
      ],
    );
  }

  Widget teamLogo(int competitionId, Team team) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          width: 30,
          height: 30,
          child: SvgPicture.network(
            widget.teamMap[competitionId][team.id].crestUrl,
          ),
        ),
      ],
    );
  }
}

我想我正在创造这样的东西?但什么时候开始?我不会在我的代码中触发或 运行 这个未来。

future = Future(() {}).then((_) {
  print("init for i =" + i.toString() + " - future.then");
  return Future.delayed(Duration(milliseconds: 100), () {
  print("init for i =" + i.toString() + " - future.delayed");
  list.add(widget.animatedList[i]);
  _listKey.currentState.insertItem(list.length - 1);
  });
  })
      .then((_) {
          print("init for i =" + i.toString() + " - future.then");
          return Future.delayed(Duration(milliseconds: 100), () {
          print("init for i =" + i.toString() + " - future.delayed");
          list.add(widget.animatedList[i]);
          _listKey.currentState.insertItem(list.length - 1);
          });
          })
      .then((_) {
                print("init for i =" + i.toString() + " - future.then");
                return Future.delayed(Duration(milliseconds: 100), () {
                print("init for i =" + i.toString() + " - future.delayed");
                list.add(widget.animatedList[i]);
                _listKey.currentState.insertItem(list.length - 1);
                });
                })
      .then((_) {
                      print("init for i =" + i.toString() + " - future.then");
                      return Future.delayed(Duration(milliseconds: 100), () {
                      print("init for i =" + i.toString() + " - future.delayed");
                      list.add(widget.animatedList[i]);
                      _listKey.currentState.insertItem(list.length - 1);
                      });
                      });

我的第二个问题是 Future.then() 与 future = Future().then 之间有什么区别吗?

谢谢。

未经仔细检查,您没有正确覆盖 initState

The official docs on State say:

If you override this, make sure your method starts with a call to super.initState().

关于您的代码和 Futures:

  • 没写过Future(() {}).
  • 写了很多有用的代码
  • 如果列表项小部件 create/own 他们的未来,这会变得更容易吗?
  • 您是否只想每 100 毫秒发生一些事情?尝试使用计时器。