Home > Software engineering >  flutter, fetching dummy local json
flutter, fetching dummy local json

Time:02-16

i have local dummy json and i want to put it on title but the variables forms does not defined, i don't understand how to call the forms

the Json and title both are in different stateless widget in same page

Json

  List<dynamic> forms = [
{
      "id": 65,
      "label": "Is this a test drive period or demonstration period?",
      "code": "survey_general",
      "type": "select_box",
      "service_id": 48,
      "client_type": "SURVEY_MITSU",
      "column_order": 1,
      "required": true,
      "options": {
        "step_number": "1",
        "step_label": "General Information",
        "options": []
      },
      "validation": null,
      "requisite": false,
      "multiple": false
    },
]

Title

Container(
              margin: EdgeInsets.fromLTRB(16, 20, 16, 8),
              child: Text(
                'Part 1: ${jsonEncode(forms['options']['step_label'])}',
                style: Constants.textTitle.copyWith(
                  fontSize: 16,
                  fontFamily: 'Nunito',
                ),
              ),
            ),

CodePudding user response:

It is not an appropriate approach to access the variables from other Widgets. The forms variable is not a local variable in Title.

There are two approaches:

  1. Put the dummy variable forms into the Title Widget
  2. Create a new class to store your dummy variable
class Dummy{

static const List<dynamic> forms = [
    {
      "id": 65,
      "label": "Is this a test drive period or demonstration period?",
      "code": "survey_general",
      "type": "select_box",
      "service_id": 48,
      "client_type": "SURVEY_MITSU",
      "column_order": 1,
      "required": true,
      "options": {
        "step_number": "1",
        "step_label": "General Information",
        "options": []
      },
      "validation": null,
      "requisite": false,
      "multiple": false
    },
];
}
Container(
              margin: EdgeInsets.fromLTRB(16, 20, 16, 8),
              child: Text(
                'Part 1: ${jsonEncode(Dummy.forms['options']['step_label'])}',
                style: Constants.textTitle.copyWith(
                  fontSize: 16,
                  fontFamily: 'Nunito',
                ),
              ),
            ),

CodePudding user response:

First Fetch content from the json file

  List formsItems = [];

  Future<void> readJson() async {
   
    final data = await json.decode(forms);
    setState(() {
      formsItems = data["options"];
    });

And after use like this

'Part 1: ${formsItems['step_label']}',
  • Related