我在运行时收到一个JSON对象列表,并基于这些JSON对象动态创建一个liderWidget列表(见下图).当我按下FloatingActionButton时,我需要在父小部件(作为主屏幕)中访问这些liderWidget的slderValues,因为这会将gliderValues保存到CSV文件中.我怎么能在不做一些非常难看的事情的情况下访问滑动值呢?由于该列表是在运行时动态创建的,并且其中可能包含大量对象,因此我不确定该如何执行此操作.
我试图用 keys 访问这些物品,但无济于事.我也不确定这是否是最好的做法.
以下代码省略了不重要的部分
class MorningSurveyScreen extends StatefulWidget {
const MorningSurveyScreen({Key? key}) : super(key: key);
@override
State<MorningSurveyScreen> createState() => _MorningSurveyScreenState();
}
class _MorningSurveyScreenState extends State<MorningSurveyScreen> {
late List<Widget> _userVariablesWidgets; // This is the variable where I save my sliderWidget list
didChangeDependencies() {
super.didChangeDependencies();
_userVariablesWidgets = UserVariablesHelper.getUserVariablesWidgets(Provider.of<UserVariablesModel>(context, listen: true).userVariables);
// This is where I start listening for my list of sliderWidgets
}
Future<void> _addEntry() async {
bool addEntry = await DialogHelper.showAddEntryDialog(context);
if (addEntry) {
await CsvDataService.addRowToCsv({
// THIS POINT IS WHERE I NEED TO ACCESS THE SLIDER VALUES
});
}
}
@override
Widget build(BuildContext context) {
//wrap in consumer
return Consumer<UserVariablesModel>(
builder: (context, userVariablesModel, child) => Stack(
children: [
Center(
child: ListView(
children: <Widget>[
// OTHER WIDGETS,
..._userVariablesWidgets // These are my sliderWidgets
],
),
),
Positioned(
bottom: 16,
right: 16,
child: FloatingActionButton(
onPressed: _addEntry,
tooltip: 'Add entry',
child: const Icon(Icons.check),
),
)
],
));
}
}
为了完整性,这些是我的SliderWidget,也是为了可读性而精简的
class SliderWidget extends StatefulWidget {
final SliderVariable sliderVariable;
// This holds sliderWidget min, max values and question label.
// However, it is unimportant for us right now
SliderWidget({Key? key, required this.sliderVariable});
@override
State<SliderWidget> createState() => _SliderWidgetState();
}
class _SliderWidgetState extends State<SliderWidget> {
late double currentSliderValue = widget.sliderVariable.min.toDouble();
// This is the value I need to access from my MorningSurveyScreen
@override
Widget build(BuildContext context) {
return Column(
children: [
// OTHER WIDGETS,
Slider(
value: currentSliderValue,
min: widget.sliderVariable.min.toDouble(),
max: widget.sliderVariable.max.toDouble(),
divisions: widget.sliderVariable.max - widget.sliderVariable.min,
label: currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() {
currentSliderValue = value;
});
},
)
],
);
}
}