Flutter Future.then在生成方法之后运行

Flutter Future.then在生成方法之后运行,flutter,dart,async-await,future,Flutter,Dart,Async Await,Future,我正在尝试将AnimatedList实现到我自己的项目中,它现在运行得非常好。我想问的是future.then如何在build方法之后运行。让我解释一下 我有一个从另一个小部件调用的小部件。我不理解的部分是init方法。小部件获取一个列表,然后每行在它们之间的指定时间内播放动画。两行动画之间有100毫秒的间隔。到现在为止,一直都还不错。但在init方法中,循环列表并在最后一个未来之上创建未来。当我调试或在init方法中的for循环之后放置一些sleep方法时(您可以看到下面的代码,您可以只关注i

我正在尝试将AnimatedList实现到我自己的项目中,它现在运行得非常好。我想问的是future.then如何在build方法之后运行。让我解释一下

我有一个从另一个小部件调用的小部件。我不理解的部分是init方法。小部件获取一个列表,然后每行在它们之间的指定时间内播放动画。两行动画之间有100毫秒的间隔。到现在为止,一直都还不错。但在init方法中,循环列表并在最后一个未来之上创建未来。当我调试或在init方法中的for循环之后放置一些sleep方法时(您可以看到下面的代码,您可以只关注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.then()和Future=Future()之间有什么区别吗

谢谢。

如果没有仔细检查,您就没有正确覆盖
initState

如果重写此项,请确保方法以调用super.initState()开始

关于您的代码和未来:
  • 我已经写了很多有用的代码,但从来没有写过
    Future((){})
  • 如果列表项小部件创建/拥有它们的未来,这会变得更容易吗
  • 你只想每100毫秒发生一次吗?尝试使用计时器

谢谢。我确实重构了我的代码,并将其分离为小部件。还可以在小部件上添加动画功能。这应该是正确的方法。
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);
                      });
                      });