首页 > 解决方案 > 为什么 Flutter 的 SpannableGrid 小部件中的 UI 不刷新以使用 String 流中的最新内容进行更新?

问题描述

  1. WallStream 类为我提供了一个字符串流,该字符串流在应用程序运行时每 1 秒递增一次
  2. 我正在使用来自https://pub.dev/packages/spannable_grid的 spannable_grid 。每当流内容发生变化时,我都希望 _buildData 也会发生变化(它确实会发生变化,因为第 27 行的打印值)。然后,我将带有更新内容的新 SpannableGridCellData 添加到列表中,并根据更新的单元格返回一个新的 SpannableGrid 小部件。我希望 UI 会更改以显示新内容,但事实并非如此。为什么不?

发布规范.yaml

  spannable_grid: ^0.1.3
  provider: ^3.1.0

主要.dart

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:spannable_grid/spannable_grid.dart';

void main() => runApp(MaterialApp(home: WallPane()));

class WallPane extends StatefulWidget {
  @override
  _WallPaneState createState() => _WallPaneState();
}

class _WallPaneState extends State<WallPane> {
  @override
  Widget build(BuildContext context) {
    return StreamProvider<String>.value(
        value: WallStream.instance.wallStateStream,
        child: new LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
          return _buildData(context, constraints);
        }));
  }

  Widget _buildData(BuildContext context, BoxConstraints constraints) {
    String content = Provider.of<String>(context);
    print(content);

    List<SpannableGridCellData> cells = List();
    cells.add(SpannableGridCellData(
      column: 1,
      row: 1,
      columnSpan: 2,
      rowSpan: 2,
      id: content,
      child: Container(
        color: Colors.lime,
        child: Center(
          child: Text(content),
        ),
      ),
    ));

    return SpannableGrid(
      columns: 4,
      rows: 4,
      cells: cells,
      spacing: 2.0,
      onCellChanged: (cell) {
        print('Cell ${cell.id} changed');
      },
    );
  }
}

class WallStream {
  static int _counter = 0;

  Stream<String> get wallStateStream async* {
    while (true) {
      yield (_counter++).toString();
      await Future.delayed(Duration(seconds: 1));
    }
  }

  WallStream._privateConstructor();
  static final WallStream instance = WallStream._privateConstructor();
}
  1. I also looked up the source code here (https://raw.githubusercontent.com/ech89899/spannablegrid-flutter/master/lib/spannable_grid.dart - I don't think it's updated with the latest code yet but I tried to use the code seen on the repo and have the same problem). I don't understand why performLayout in class _SpannableGridDelegate extends MultiChildLayoutDelegate is called whenever I see the stream data change but the cell.Child doesn't have the latest data.

Please help. Thank you in advance.

标签: flutterdart

解决方案


I am author of SpannableGrid package. Thank you for using it, and for the feedback provided.

There was a bug in the package. I've added a fix for this. Please check if the version 0.1.4+ will work for you.


推荐阅读