Tinovimba Mawoyo
Tinovimba Mawoyo

Reputation: 410

Flutter Populate items into listView from sharedPreferenes json

I am trying to populate a gridview.builder with items i have in an adapter class. I have successfully done that by hard coding the items. My model class is like this :

class portfolioModel{

  String symbol, openingP, closingP,holdings, shareNames;

  portfolioModel(
      {
        required this.symbol,
        required this.openingP,
        required this.closingP,
        required this.holdings,
        required this.shareNames,

      }
      );


}

Then my adapter is like this

class PortfolioAdapter {

  List getPortfolio() {


    return [
      portfolioModel(
        symbol: "AFDS.ZW",
        openingP: "310.23",
        closingP: "310.23",
        holdings: "200",
        shareNames: "African Distillers",

      ),

      portfolioModel(
        symbol: "ECO.ZW",
        openingP: "210.23",
        closingP: "111.30",
        holdings: "100",
        shareNames: "Econet Zimbabwe",

      ),

      portfolioModel(
        symbol: "SIM.ZW",
        openingP: "310.23",
        closingP: "411.30",
        holdings: "1000",
        shareNames: "Simbisa Holdings",

      ),


    ];
  }
}

I am then populating the adapter items successfully in a gridview. But now i want to replace the items i have in my adapter with a json object i have. The json object is like this

{
"portfolio": {
"holdings": [
{
"CSDNUMBER": "201102042587-0001",
"CLIENTNAME": "MAWOYO T",
"SYMBOL": "FCA.ZW",
"HOLDINGS": "8180900",
"SHARENAME": "FIRST CAPITAL BANK LIMITED",
"SYMBOLID": "X0",
},
{
"CSDNUMBER": "201102042587-0001",
"CLIENTNAME": "MAWOYO T",
"SYMBOL": "SIM.ZW",
"SYMBOLID": "Y1",
"HOLDINGS": "600",
"SHARENAME": "SIMBISA BRANDS LIMITED",

}
],
"openingPrice": {
"X0": "3.6348",
"Y1": "94.9"
},
"closingPrice": {
"X0": "3.6054",
"Y1": "90.0163"
}
}
} 

HOW do i replace the Adapter dummy data i have put with the json data i have provided

Upvotes: 1

Views: 130

Answers (1)

Faiz
Faiz

Reputation: 6960

you can do it like this.

import 'package:flutter/material.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<portfolioModel> _list = [];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    (PortfolioAdapter()).getPortfolio().then((mlist) {
      print(_list);
      setState(() {
        _list.addAll(mlist);
      });
    }).catchError((e) {
      print(e);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _list.isNotEmpty
          ? ListView.builder(
              itemCount: _list.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(_list[index].shareNames),
                  subtitle: Text(_list[index].holdings),
                );
              })
          : const Center(child: Text('loading...')),
    );
  }
}

class portfolioModel {
  String symbol, openingP, closingP, holdings, shareNames;

  portfolioModel({
    required this.symbol,
    required this.openingP,
    required this.closingP,
    required this.holdings,
    required this.shareNames,
  });

  factory portfolioModel.fromJson(Map<String, dynamic> json,
      {openingP, closingP}) {
    return portfolioModel(
      symbol: json['SYMBOL'],
      openingP: openingP,
      closingP: closingP,
      holdings: json['HOLDINGS'],
      shareNames: json['SHARENAME'],
    );
  }
}

class PortfolioAdapter {
  final String jsonData = '''{
   "portfolio":{
      "holdings":[
         {
            "CSDNUMBER":"201102042587-0001",
            "CLIENTNAME":"MAWOYO T",
            "SYMBOL":"FCA.ZW",
            "HOLDINGS":"8180900",
            "SHARENAME":"FIRST CAPITAL BANK LIMITED",
            "SYMBOLID":"X0"
         },
         {
            "CSDNUMBER":"201102042587-0001",
            "CLIENTNAME":"MAWOYO T",
            "SYMBOL":"SIM.ZW",
            "SYMBOLID":"Y1",
            "HOLDINGS":"600",
            "SHARENAME":"SIMBISA BRANDS LIMITED"
         }
      ],
      "openingPrice":{
         "X0":"3.6348",
         "Y1":"94.9"
      },
      "closingPrice":{
         "X0":"3.6054",
         "Y1":"90.0163"
      }
   }
}''';

  Future<List<portfolioModel>> getPortfolio() async {
    List<portfolioModel> list = [];

    final body = json.decode(jsonData);

    body['portfolio']['holdings'].forEach((item) async {
      list.add(portfolioModel.fromJson(item,
          openingP: body['openingPrice'].toString(),
          closingP: body['closingPrice'].toString()));
    });

    return list;
  }
}

Upvotes: 1

Related Questions