How can I change "1" in busData['data'][1]['directions']
to id passed from another class? I want to make this dynamic. I have 3 cities in previous view and I want to pass it's number automatically depending on which city I choose.
`
class Bus extends StatefulWidget {
final String city;
final int id;
Bus(this.city, this.id);
@override
State<Bus> createState() => _BusState();
}
class _BusState extends State<Bus> {
List _bus = [];
Future<void> readJsonFile() async {
final String res = await rootBundle.loadString('assets/bus.json');
final busData = await json.decode(res);
setState(() {
_bus = busData['data'][1]['directions'];
});
}
`
My JSON looks like this:
`
{"data":
[{
"city": "New York",
"directions": [
{
"number": "1"
},
{
"number": "2"
},
{
"number": "3"
}
},
{
"city": "Warsaw",
"directions": [
{
"numer": "101",
`
Right now I am choosing manually 0 = New York or 1 = Warsaw. How can I change it? Any help?
I tried to pass id from Bus class to _BusState using `
State<Bus> createState() => _BusState(int id);
` but I had problem with using it in _BusState class.
CodePudding user response:
Try this,
class Bus extends StatefulWidget {
final String city;
final int id;
final int number;
Bus(this.city, this.id, this.number);
@override
State<Bus> createState() => _BusState();
}
class _BusState extends State<Bus> {
List _bus = [];
Future<void> readJsonFile() async {
final String res = await rootBundle.loadString('assets/bus.json');
final busData = await json.decode(res);
setState(() {
_bus = busData['data'][widget.number]['directions'];
});
}