Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change ID from JSON automatically in setState?

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'];
    });
  }

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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'];
    });
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading