NotifyListeners()在Flutter中无法正常工作

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

在我的启动画面中,我正在从我的模型类中调用一个方法(从API中获取一些数据并将它们放入列表中)。它可以工作并生成列表。但是我无法将此列表发送到我的listview小部件。这是相关代码;

SplashScreen部分正在调用模型类方法(getFixtures)

 class _SplashScreenState extends State<SplashScreen> {
  List<Fixture> fixtureList = List<Fixture>();
  FixtureData callFixtureData = FixtureData();

  @override
  void initState() {
    super.initState();
    SplashScreen.fixtureData = getFixture();
    Timer(
      Duration(seconds: 5),
      () => Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (BuildContext context) => WelcomeScreen(),
        ),
      ),
    );
  }

  Future<List<Fixture>> getFixture() async {
    fixtureList = await callFixtureData.getFixtures();
    return fixtureList;
  }

Model类部分;我看到列表不为空且正确]]

class FixtureData extends ChangeNotifier {

  List<Fixture> fixtures = List<Fixture>();
  List<Fixture> bets = List<Fixture>();

  //to show in FAB at HomeScreen
  int get betCount {
    return bets.length;
  }

  Future<List<Fixture>> getFixtures() async {
    fixtures = await FootballApi.getFixtureData();
    print(fixtures[0].homeTeam);
    notifyListeners();
    return fixtures;
  }

ListView部分。我用最终的夹具调用列表= fixtureData.fixtures [index];但是什么也没发生。我想念什么?

class FixtureList extends StatelessWidget {
  final dateFormat = DateFormat('MMMd');
  final timeFormat = DateFormat('Hm');

  @override
  Widget build(BuildContext context) {
    return Consumer<FixtureData>(
      builder: (context, fixtureData, child) {
        return ListView.builder(
          itemBuilder: (context, index) {
            final fixture = fixtureData.fixtures[index];
            return FixtureTile(
              date: dateFormat.format(fixture.dateTime),
              time: timeFormat.format(fixture.dateTime),
              homeTeam: fixture.homeTeam,
              awayTeam: fixture.awayTeam,
              homeOdds: fixture.homeOdds,
              drawOdds: fixture.drawOdds,
              awayOdds: fixture.awayOdds,
              isHomeSelected: fixture.homeSelected,
              isDrawSelected: fixture.drawSelected,
              isAwaySelected: fixture.awaySelected,
              homeCallBack: () => fixtureData.updateSelection(fixture, 'home'),
              drawCallBack: () => fixtureData.updateSelection(fixture, 'draw'),
              awayCallBack: () => fixtureData.updateSelection(fixture, 'away'),
            );
          },
          itemCount: fixtureData.fixtures.length,
        );
      },
    );
  }
}

在启动画面中,我正在从模型类中调用一个方法(从API中获取一些数据并将它们放入列表中)。它可以工作并生成列表。但我无法将此列表发送到我的列表视图中...

flutter dart provider
1个回答
0
投票

您应该先阅读提供者documentationsample,这是很错误的,您从未将FixtureData.fixtures设置为值,但是在ListView中您想使用它!

© www.soinside.com 2019 - 2024. All rights reserved.