当我使用无状态小部件数组制作ListView时,我没有收到任何错误,一切正常。但是,当我将有状态的小部件放入数组中并通过滚动使其重新呈现该小部件以使其在视图之外结束时,就会出现错误。
我在ListView和ListView.builder上尝试过,似乎没有什么区别。我认为问题出在文本上,所以我尝试删除所有Text构造函数,但没有区别。该小部件确实会进行初始化和处理,但不会重新初始化。
class CustomSettingsScreen extends StatefulWidget {
static const String routeName = "/settings";
@override
CustomSettingsScreenState createState() =>CustomSettingsScreenState();
}
class CustomSettingsScreenState extends State<CustomSettingsScreen> {
@override
void initState() {
super.initState();
}
final listElements = {
Divider(height: 500),
VibrateStartRecordingEnablePreference(
preferenceKey: PreferenceKeys.keyVibrateStartRecordingEnable,
),
Divider(height: 500),
Divider(height: 500),
Divider(height: 500),
Divider(height: 500),
};
};
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Settings"),
),
body: ListView.builder(
itemCount: listElements.length,
itemBuilder: (BuildContext context, int index) {
return listElements.elementAt(index);
},
),);
}
}
class VibrateStartRecordingEnablePreference extends StatefulWidget {
VibrateStartRecordingEnablePreference({
Key key,
@required this.preferenceKey,
});
final preferenceKey;
final _VibrateStartRecordingEnablePreferenceState
_vibrateStartRecordingEnablePreferenceState =
new _VibrateStartRecordingEnablePreferenceState();
@override
_VibrateStartRecordingEnablePreferenceState createState() =>
_vibrateStartRecordingEnablePreferenceState;
}
class _VibrateStartRecordingEnablePreferenceState extends State<VibrateStartRecordingEnablePreference> {
String _title = "Vibrate at the start of recording";
String _subtitleOn = "Vibrates once upon start of recording";
String _subtitleOff = "Will not vibrate at start";
bool _value = true;
String _getSubtitle() {
if (_value)
return _subtitleOn;
else
return _subtitleOff;
}
void _updateValue(bool value) {
Settings().save(widget.preferenceKey, value);
setState(() {
_value = value;
});
}
@override
void initState() {
//Update the values and text
Settings().getBool(widget.preferenceKey, true).then((value) {
setState(() {
_value = value;
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return new SwitchListTile(
secondary: const Icon(Icons.vibration),
title: Text("$_title"),
subtitle: Text(_getSubtitle()),
value: _value,
onChanged: (value) {
_updateValue(value);
},
);
}
}
调试器中的错误
The following assertion was thrown building NotificationListener<KeepAliveNotification>: 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4006 pos
12: '_state._widget == null': is not true.
这是正在发生的事情的视频。 https://webm.red/6ZTH
答案 0 :(得分:0)
_vibrateStartRecordingEnablePreferenceState
存储在VibrateStartRecordingEnablePreference
内部,这是错误的。
框架尝试将状态实例附加到小部件,但是状态已附加到一个。因此会导致异常。
每次在StatefulWidget中调用createState()
时,您都必须返回一个新的状态实例