Issue
`List<Widget> _dataList = [
DataCard(
start: 0,
end: 6,
),
DataCard(
start: 2,
end: 8,
),
DataCard(
start: 4,
end: 20,
)
];`
dataCard
is basically returns a GestureDetector
widget with Card
widget which shows the start and end values.
What I want to be able to do is to change the values of start / end after displaying the widgets on screen. How do I access the properties of any dataCard
in the list?
This is the DataCard class:
class DataCard extends StatelessWidget {
DataCard({this.start, this.end, this.key});
final int start;
final int end;
final Key key;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
print(key);
},
child: Card(
key: key,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text(
'Start: $start',
style: TextStyle(
fontSize: 40,
),
),
Text(
'End: $end',
style: TextStyle(
fontSize: 40,
),
),
],
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
}
}
For example, I want to change only the second DataCard
widget’s start and end values when I click the Floating Action Button. Is there a way to do that? Thank you!
The end-goal is for users to be able to add a DataCard
to the list wherein start and end values are also determined by them. Afterwards, the values of the DataCard
are to be adjusted without user intervention.
Solution
Your question connected to the big theme that called app state management.
Learn about it beginning from stateful widget, inherited widget, provider package, and BLoC pattern. (from simplest to hardest)
This is a video made by flutter team about stateful widget https://youtu.be/AqCMFXEmf3w.
going back to your question, simple example of using stateful widget:
class _MyHomePageState extends State<MyHomePage> {
var list = <List<int>>[
[1, 6],
[2, 8],
[4, 20]
];
void _incrementSecondCardStartParametr() {
setState(() {
list[1][0] += 1;
});
}
Function decrementEndParametr(idx) => () => setState((){
list[idx][1] -= 1;
});
@override
Widget build(BuildContext context) {
List<Widget> _widgets = list
.map((data) => DataCard(
start: data[0],
end: data[1],
decrementEndParametr: decrementEndParametr(list.indexOf(data))
))
.toList();
return Scaffold(
appBar: AppBar(
title: Text('List Example'),
),
body: Center(
child: Column(children: _widgets),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementSecondCardStartParametr,
child: Icon(Icons.add),
),
);
}
}
class DataCard extends StatelessWidget {
DataCard({this.start, this.end, this.key, this.decrementEndParametr});
final Function decrementEndParametr;
..
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: decrementEndParametr,
..
Answered By – Kherel
Answer Checked By – Senaida (FlutterFixes Volunteer)