下面的代码有问题。我在这里得到消息'setState()or markNeedsBuild()called during build',我不知道该怎么做才能使代码正确运行。这个想法是创建一个列表,存储激活的ToggleButton的索引,以在不同的屏幕上不同的地方显示相同的信息。非常感谢你的帮助。
如果需要更多的代码或信息,我很乐意发布。
class ToggleButtonUsers extends StatefulWidget {
@override
_ToggleButtonUsersState createState() => _ToggleButtonUsersState();
}
class _ToggleButtonUsersState extends State<ToggleButtonUsers> {
bool vertical = false;
List<bool> selectedUser = [];
List<Widget> selectedChildren = [];
@override
void initState() {
final userModelData = Provider.of<UserModel>(context, listen: false);
final userModel = userModelData.items;
final toggleModelData = Provider.of<ToggleProvider>(context, listen: false);
final toggleModel = toggleModelData.items;
final indexUserData = Provider.of<ToggleProvider>(context, listen: false);
final indexUser = indexUserData.indexUser;
for (var index = 0; index < toggleModel.length; index += 1) {
debugPrint('aktueller Index: ' + index.toString());
selectedUser = List.generate(
toggleModel.length,
(index) => index == 0 ? true : false,
);
toggleModelData.addIndex(0);
selectedChildren = List.generate(
toggleModel.length,
(index) => UserItem(
userModel[index].id,
userModel[index].name,
userModel[index].image,
userModel[index].color,
),
);
//indexUserData.addIndex(0);
}
super.initState();
}
@override
Widget build(BuildContext context) {
final indexUserData = Provider.of<ToggleProvider>(context);
final indexUser = indexUserData.indexUser;
debugPrint('Inhalt UserIndex ist: ' + indexUser.toString());
return Padding(
padding: const EdgeInsets.all(8.0),
child: ToggleButtons(
constraints: const BoxConstraints(
minHeight: 40.0,
maxHeight: 45,
minWidth: 80.0,
maxWidth: 85,
),
borderRadius: BorderRadius.circular(30),
fillColor: Colors.green,
//disabledBorderColor: Colors.red,
direction: vertical ? Axis.vertical : Axis.horizontal,
onPressed: (int index) {
if (mounted) {
setState(() {
selectedUser[index] = !selectedUser[index];
});
}
selectedUser[index] == true
? indexUserData.addIndex(index)
: indexUserData.removeIndex(10);
debugPrint('selected User ist nun: ' + selectedUser.toString());
debugPrint('der gecklickte Index ist: ' + index.toString());
},
children: selectedChildren,
isSelected: selectedUser,
),
);
}
}
1条答案
按热度按时间pobjuy321#
我猜这是因为您调用了notifyListeners()或类似的方法来更新initState中的ui。这里的问题是,ui仍然在您的initState中构建...你可以尝试将
toggleModelData.addIndex(0);
) Package 在addPostFrameCallback中:这将在呈现Frame后调用它