简体   繁体   English

Flutter 将项目从 sharedPreferenes json 填充到 listView

[英]Flutter Populate items into listView from sharedPreferenes json

I am trying to populate a gridview.builder with items i have in an adapter class.我正在尝试使用适配器类中的项目填充 gridview.builder。 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.然后我在 gridview 中成功填充适配器项目。 But now i want to replace the items i have in my adapter with a json object i have.但是现在我想用我拥有的 json 对象替换我的适配器中的项目。 The json object is like this json对象是这样的

{
"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我如何用我提供的 json 数据替换我放置的适配器虚拟数据

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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM