gpt4 book ai didi

flutter - 在小部件init中设置提供程序不起作用

转载 作者:行者123 更新时间:2023-12-03 03:59:57 24 4
gpt4 key购买 nike

我试图在初始化小部件时设置提供程序变量,以使小部件具有适当的数据。这样做时出现错误。这是代码:

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
builder: (context) => ListManager(),
child: MaterialApp(
title: 'crud-to-do',
home: Home(), // Home calls ListWidget()
),
);
}
}

class ListWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final listManager = Provider.of<ListManager>(context);
listManager.list = [
ListItem(title: 'myTtitle', description: 'My desc', id: '1324j323e')
];

if (listManager.list.isEmpty) return Text("hey");
return Text(listManager.list[0].title);
}
}

这可行,但出现错误:
flutter: ══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY ╞════════════════════════════════════════════════════════
flutter: The following assertion was thrown while dispatching notifications for ListManager:
flutter: setState() or markNeedsBuild() called during build.
flutter: This ChangeNotifierProvider<ListManager> widget cannot be marked as needing to build because the
flutter: framework is already in the process of building widgets. A widget can be marked as needing to be
flutter: built during the build phase only if one of its ancestors is currently building. This exception is
flutter: allowed because the framework builds parent widgets before children, which means a dirty descendant
flutter: will always be built. Otherwise, the framework might not visit this widget during this build phase.
flutter: The widget on which setState() or markNeedsBuild() was called was:
flutter: ChangeNotifierProvider<ListManager>
flutter: The widget which was currently being built when the offending call was made was:
flutter: ListWidget
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 Element.markNeedsBuild.<anonymous closure>
package:flutter/…/widgets/framework.dart:3680
flutter: #1 Element.markNeedsBuild
package:flutter/…/widgets/framework.dart:3695
flutter: #2 State.setState

因此,因此我尝试将 initState包裹在 listManager.list的设置周围,如下所示:
@override
void initState() {
listManager.list = [
ListItem(title: 'myTtitle', description: 'My desc', id: '1324j323e')
];
}

但是我收到一个错误消息:

The declaration 'initState' isn't referenced.



在这两种情况下我都做错了什么?设置 provider的正确方法是什么?

最佳答案

在您的构建方法中,使用Provider.of<ListManager>(context, listen: false)防止重建。

默认情况下,listen设置为true,并在模型更改时触发重建,这将在build()方法或initState()中引发异常。

关于flutter - 在小部件init中设置提供程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58003758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com