当继承模型中的数据方面发生更改时,如何"notify"颤振列表视图.builder



在我的继承模型中,我有一个idList,它是一个字符串列表。

在卡片页面我有

Widget build(BuildContext context) {
List<String> idList =
ModelData.of(context, aspect: ModelAspects.idList).idList;
return ListView.builder(
itemBuilder: _docCardBuilder,
itemCount: idList.length,
);
}
Widget _docCardBuilder(BuildContext context, int itemIndex) {
String docId = ModelData.of(context, aspect: ModelAspects.idList)
.idList[itemIndex];
Map cardData = repo.getById(docId);
return DocCard(
key: Key(cardData['id']),
publishedDate: cardData['date'],
description: cardData['description'],
onTap: () => widget.showDetail(cardData['id']),
);
}

And elsewhere:
Future<bool> fetchData(ValueChanged<List<String>> onIdListChange}) async {
bool savedValue = isBusy;
try {
isBusy = true; // Show Modal Spinner;
setState(() {});
await repo.refresh();
onIdListChange(repo.dataCache.idList);  // Callback to the InheritedModel
return true;
} finally {
isBusy = savedValue;  // Maybe clear the spinner
setState(() {});
}
return false;
}

我的感觉是listview.builder本身不会收到更改的通知,因为它会显示原始卡片列表,直到应用程序终止并重新启动。

如果你想在模型更改时得到连续的通知,你应该使用StreamBuilder,如果是一次性获取数据,那就去FutureBuilder。

当数据模型发生更改时,不会通知ListviewBuilder

我不完全确定您希望实现什么,但是您对setState((的使用似乎有点有趣。

你的微调器甚至像这样工作吗?

你应该像这样使用它:

setState(() {
isBusy = true; // Show Modal Spinner;
});

然后引擎将确定哪些构建函数依赖于 isBusy,并仅重建这些小部件。

就未更新的字符串列表而言,我建议使用"ChangeNotifier"查看提供程序模式。

这将做你所希望的。

请参阅此链接: https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple#changenotifier

我研究了如何"订阅"ListView Builder以更改列表。

需要两件事:1. 不使用
外部控制器为 listview 提供原始数据,而是使用存储在父级状态中的缓存来提供 listview "构建器"功能(并使列表视图使用它(
2.在状态的didChangeDependencies方法中更新此缓存。

基本上:

import 'package:flutter/material.dart';
class CardDataModel {
final String id;
final String caption;
CardDataModel(this.id, this.caption);
}
class SomePage extends StatefulWidget {
@override
_SomePageState createState() => _SomePageState();
}

class _SomePageState extends State<SomePage> {
List<CardDataModel> cardData;  // setState after changing this to trigger rebuild
Widget _cardBuilder(BuildContext context, int itemIndex) {
final String cardId = cardData[itemIndex].id;
return DocCard(
key: Key(cardId), // Help Flutter know which widget it what
data: cardData[itemIndex]
);
}

@override
void didChangeDependencies() {  // Magic happens here
super.didChangeDependencies();
cardData = TheInheritedModel.of(context, aspect: CARD_DATA_ASPECT).data;
setState(() {}); // AFAIK this will only be called when the widget is mounted
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: _cardBuilder,
itemCount: cardData.length,  // Depends expressly on the state property
);
}
}
class DocCard extends StatelessWidget {
final CardDataModel data;
const DocCard({Key key, this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(child: Text(data.caption),);
}
}

最新更新