Data from .json in Flutter GetX

Data from .json in Flutter GetX

GetX is the state management, but this is using CLI

In this blog we'll be loading data from a json file and showing it to view, the steps include

  • Creating a .json File
  • Resourcing in pubspec.yaml
  • Creating Model
  • Loading the asset
  • Mapping the data
  • Showing it in the view

Step 0:Creating the project

0.1 - open your terminal 0.2 - run command get create project 0.3 - image.png 0.4 - Select Flutter Project, then enter project name and your package name 0.5- Select Swift for iOS 0.6 - Kotlin for Android 0.7 - Select yes for null safe 0.8 - Use Dart Linter (Recommended) 0.9 - For better folder structure, first paste this at the bottom in the pubspec.yaml get_cli: separator: . sub_folder: false image.png

0.10 - After this you have no subfolders and a readable file, then just go ahead and select the GetXPattern -- PROJECT CREATED AND READY TO GO--

Step 1: Generating data and mapping it

1.1 Create a file with path 'assets/json/all-stock-data.json' inside your project directory 1.2.0 Add this sample dataset inside the file

{
    "stocks": [
        {
            "name": "Reliance Limited Oil and Technology.",
            "allTimeHigh": 3000,
            "peRatio": 39,
            "marketCap": "19 Lakh Crores",
            "risk": "Low",
            "InvestmentPeriod": "5 to 10 Years"
        },
        {
            "name": "Bajaj Finance Banking.",
            "allTimeHigh": 3000,
            "peRatio": 39,
            "marketCap": "19 Lakh Crores",
            "risk": "High",
            "InvestmentPeriod": "4 to 12 Years"
        },
        {
            "name": "Asian Paints Commodities",
            "allTimeHigh": 3000,
            "peRatio": 39,
            "marketCap": "19 Lakh Crores",
            "risk": "Low",
            "InvestmentPeriod": "8 to 80 Years"
        }
    ]
}

1.2.1 Remember to import this in pubspec.yaml

flutter: 
  assets: 
    - assets/json/

1.2.2 To proceed further we'll first create a model for this file Run the command

get generate model on data with assets/json/all-stock-data.json

1.2.3 Verify the model (only for those who face some issues in) raw.githubusercontent.com/hrithikwins/stock..

1.2.4

1.3.0 In home.controller.dart

1.3.1 Import rootBundle

import 'package:flutter/services.dart' show rootBundle;

1.3.2 Import the model

import 'package:stock_it/app/data/all_stock_data.model.dart';

1.3.3 declare the Variable for storing data

  Rx<AllStockData> allStocksData = AllStockData().obs;

1.3.4 In the same file you have an 'onReady()' function

  @override
  void onReady() {
    feedValues();
    super.onReady();
  }

1.3.5 Now this feedValues() is not yet created, we're going to define it

  void feedValues() async {
    try {
      var feedLoadedData = await rootBundle.loadString("assets/json/all-stock-data.json");
      print("feeded value");
      allStocksData.value = AllStockData.fromJson(jsonDecode(feedLoadedData));
    } catch (e) {
      Get.snackbar("Server Error", "error in getting stock data");
      print("feed value error" + e.toString());
    }
  }

1.3.6 You can also split this code as

  void feedValues() async {
    try {
      var feedLoadedData = await loadJson("assets/json/all-stock-data.json");
      print("feeded value");
      allStocksData.value = AllStockData.fromJson(jsonDecode(feedLoadedData));
    } catch (e) {
      Get.snackbar("Server Error", "error in getting stock data");
      print("feeded value error" + e.toString());
    }
  }

//creating this function intending that you'll be loading multiple files
  loadJson(jsonFile) {
    return rootBundle.loadString(jsonFile);
  }

1.3.7 The complete file would be as raw.githubusercontent.com/hrithikwins/stock..

Step 2: showing in the front-end

This is your home.view.dart

import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../routes/app_pages.dart';
import 'home.controller.dart';

class HomeView extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _artificialAppBar(),
            Padding(
              padding: const EdgeInsets.all(18.0),
              child: Text(
                "Explore Stocks",
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Expanded(
              child: Obx(
                () => controller.allStocksData.value.stocks != null
                    ? ListView(
                        children: [
                          for (var index = 0;
                              index <
                                  controller.allStocksData.value.stocks!.length;
                              index++)
                            _stockTile(
                              controller.allStocksData.value.stocks![index],
                              index,
                            ),
                        ],
                      )
                    : Wrap(),
              ),
            ),
            // ElevatedButton(
            //   onPressed: () => {controller.feedValues()},
            //   child: Text("gee"),
            // ),
          ],
        ),
      ),
    );
  }

  Widget _artificialAppBar() {
    return Row(
      children: [
        Container(
          padding: EdgeInsets.symmetric(
            vertical: 20,
            horizontal: 13,
          ),
          child: Text(
            "Hii, Good " + controller.greetings() + "!",
            style: TextStyle(
              fontSize: 30,
              color: Color.fromARGB(255, 44, 0, 146),
              fontWeight: FontWeight.w800,
            ),
          ),
        ),
      ],
    );
  }

  _stockTile(stockData, index) {
    return Card(
      child: Container(
        padding: EdgeInsets.symmetric(
          vertical: 20,
          horizontal: 13,
        ),
        child: Text(
          stockData.name,
          style: TextStyle(
            fontSize: 12,
            color: Color.fromARGB(255, 44, 0, 146),
            fontWeight: FontWeight.w800,
          ),
        ),
      ),
    );
  }
}

Thanks for Reading, if you loved the content, follow on hashnode for more such flutter content,

Clone the repository from https://github.com/hrithikwins/stock_it_getx Would love to connect with you on Twitter : )

Did you find this article valuable?

Support Hrithik Tiwari by becoming a sponsor. Any amount is appreciated!