如何在详细屏幕中查看项目的详细信息 - Flutter

Posted

技术标签:

【中文标题】如何在详细屏幕中查看项目的详细信息 - Flutter【英文标题】:How can I view the details of an item in a detailed screen - Flutter 【发布时间】:2020-10-15 21:26:39 【问题描述】:

我是新来的,这个错误给了我一个严重的噩梦。我有一个名为 Anchors 的项目卡片列表。这些项目来自属于登录用户的共享首选项文件。在共享偏好 Json 文件中,每个锚点都嵌套了一个或多个分发中心。全部以 JSON 形式存储在共享首选项中。现在,我能够在第一个屏幕上恭敬地迭代锚点,但我面临的挑战是当我单击查看锚点详细信息按钮而不是带我到详细信息页面时,我可以查看该锚点的详细信息并进行迭代该锚点的配送中心没有,而是将整个锚点带到那里。我尝试仅将一个 id 解析到详细信息页面,以便可以迭代该锚点的嵌套对象,但它仍然无法正常工作。错误消息说:type 'int' is not a subtype of type 'List' But if I remove [i]['Oid'] from the link to the details screen 它把整个数据放在那里。它们都在两个不同的屏幕上。请问有人可以帮帮我吗?

JSON 格式:

 "Anchors": [
    
      "Oid": 11,
      "Name": "MAIZE ASSOCIATION OF NIGERIA",
      "Acronym": "MAAN",
      "DistributionCentres": [
        
          "Oid": 11,
          "Name": "Logo Centre (Zone A)",
          "Address": "Private Warehouse, Ugba, Logo LGA"
        ,
        
          "Oid": 12,
          "Name": "Makurdi Centre (Zone B)",
          "Address": "Ministry of Agric, Makurdi "
        ,
        
          "Oid": 13,
          "Name": "Oturkpo Centre (Zone C)",
          "Address": "Private Warehouse, Oturkpo"
        ,
        
          "Oid": 15,
          "Name": "Borno MAAN centre",
          "Address": "Bolori Store, Flavour Mill, Behind Vita Foam, Maiduguri"
        ,
        
          "Oid": 18,
          "Name": "Bauchi Centre",
          "Address": "BASPD, Dass Road, Bauchi"
        
      ],
      "NoOfDistributionCentres": 5
    ,
    
      "Oid": 2,
      "Name": "MAIZE GROWERS, PROCESSORS AND MARKETERS ASSOCIATION OF NIGERIA",
      "Acronym": "MAGPAMAN",
      "DistributionCentres": [
        
          "Oid": 2,
          "Name": "Guma Centre",
          "Address": "P 32, 2nd Avenue Federal Housing Estate, N/Bank, Makurdi"
        ,
        
          "Oid": 3,
          "Name": "Logo Centre",
          "Address": "Terhemen Akema Storage Facility, Ugba, Logo LGA"
        ,
        
          "Oid": 5,
          "Name": "Oturkpo Centre",
          "Address": "Grain Store, Lower Benue Okele Project, Otukpo"
        ,
        
          "Oid": 6,
          "Name": "Gboko Centre",
          "Address": "K3 New Road, Opposite former coca cola plant. Solar Schools Street, Gboko"
        ,
        
          "Oid": 7,
          "Name": "Gwer East Centre",
          "Address": "Ahua Shardye's Warehouse, Behind Sylkan Filling Station, Ikpayongo , G/East LGA"
        ,
        
          "Oid": 8,
          "Name": "Kwande Centre",
          "Address": "KM 3, Adagi Road, Adikpo"
        ,
        
          "Oid": 9,
          "Name": "Ohimini Centre",
          "Address": "Ajoga Oglewu, Ohimini"
        ,
        
          "Oid": 10,
          "Name": "Oju Centre",
          "Address": "Behind Town Hall, Ohuhu owo, Oju LGA"
        
      ],
      "NoOfDistributionCentres": 8
    
  ],

锚页面:

import 'package:erg_app/Details.dart';
import 'package:flutter/material.dart';
import 'package:erg_app/Widgets/nav-drawer.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MaterialApp(
      home: AnchorsPage(),
    ));

class AnchorsPage extends StatefulWidget 
  @override
  _MyHomeState createState() => _MyHomeState();


List<Anchor> _parseAnchors(Map<String, dynamic> map) 
  final anchors = <Anchor>[];
  for (var anchorMap in map['Anchors']) 
    final anchor = Anchor.fromMap(anchorMap);
    anchors.add(anchor);
  
  return anchors;


class Anchor 
  final int oId;
  final String name;
  final String acronym;
  final List<DistributionCenter> distributionCenters;

  const Anchor(
    @required this.oId,
    @required this.name,
    @required this.acronym,
    @required this.distributionCenters,
  );

  factory Anchor.fromMap(Map<String, dynamic> map) 
    final distributionCenters = <DistributionCenter>[];
    for (var distribution in map['DistributionCentres']) 
      final distributionCenter = DistributionCenter.fromMap(distribution);
      distributionCenters.add(distributionCenter);
    

    return Anchor(
      oId: map['Oid'] as int,
      name: map['Name'] as String,
      acronym: map['Acronym'] as String,
      distributionCenters: distributionCenters,
    );
  


class DistributionCenter 
  final int id;
  final String name;
  final String address;

  const DistributionCenter(
    @required this.id,
    @required this.name,
    @required this.address,
  );

  factory DistributionCenter.fromMap(Map<String, dynamic> map) 
    return DistributionCenter(
      id: map['Oid'] as int,
      name: map['Name'] as String,
      address: map['Address'] as String,
    );
  



class _MyHomeState extends State<AnchorsPage> 

 var user;
 var userData;
 List anchors = [];
  @override
  void initState() 
    _getUserAnchor();
    super.initState();
  

  _getUserAnchor() async 
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var userJson = localStorage.getString('loginRes');
    user = json.decode(userJson);
    setState(() 
      anchors = user['Anchors'];
    );
    print(anchors);
    setState(() 
      userData = anchors;
    );
  



  @override
  Widget build(BuildContext context) 
    return Scaffold(
      drawer: NavDrawer(),
      appBar: AppBar(
        title: Text('Anchors Details'),
        iconTheme: IconThemeData(color: Colors.white),
        backgroundColor: Colors.green,
      ),
      body: Container(
        padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
        child: ListView(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                Icon(Icons.card_membership,
                    size: 35, color: Colors.orange[400]),
                Text(
                  'Assigned Anchors',
                  style: TextStyle(color: Colors.orange[400], fontSize: 25),
                  
                ),
              ],
            ),
            
            ListView.builder(
                shrinkWrap: true,
                itemCount: anchors.length,
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int i) 
                  return Padding(
                    padding: const EdgeInsets.all(10.0),
                    ////////////// 1st card///////////

                    child: Card(
                      elevation: 4.0,
                      color: Colors.grey[100],
                      margin: EdgeInsets.only(
                          left: 10, right: 10, top: 20, bottom: 10),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10)),
                      child: Container(
                        padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
                        width: MediaQuery.of(context).size.width,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Container(
                                      width: 50.0,
                                      height: 50.0,
                                      decoration: new BoxDecoration(
                                          shape: BoxShape.circle,
                                          image: new DecorationImage(
                                              fit: BoxFit.cover,
                                              image: AssetImage(
                                                  'assets/images/user.png')))),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Text(
                                  anchors[i]['Acronym'],
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    color: Color(0xFF9b9b9b),
                                    fontSize: 20,
                                    decoration: TextDecoration.none,
                                    fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ],
                            ),
                            Container(width: 10),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Allocated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 70, top: 12),
                                  child: Text(
                                    anchors[i]['Oid'].toString(),
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Validated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 70, top: 12),
                                  child: Text(
                                    anchors[i]['Oid'].toString(),
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Non Validated Farmers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 40, top: 12),
                                  child: Text(
                                    anchors[i]['Oid'].toString(),
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Distribution Centers:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 60, top: 12),
                                  child: Text(
                                    anchors[i]['Oid'].toString(),
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Colors.grey[700],
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 10, top: 10),
                                  child: Text(
                                    'Daily Inventory Status:',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color: Color(0xFF9b9b9b),
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding:
                                      const EdgeInsets.only(left: 50, top: 12),
                                  child: Text(
                                    '3',
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      color:Colors.green,
                                      fontSize: 14.0,
                                      decoration: TextDecoration.none,
                                      fontWeight: FontWeight.normal,
                                      
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Container(
                              height: 20,
                            ),
                            Row(
                              children: <Widget>[
                                /////////// Buttons /////////////

                                Padding(
                                  padding: const EdgeInsets.all(10.0),
                                  child: FlatButton(
                                          child: Padding(
                                            padding: EdgeInsets.only(
                                                top: 8,
                                                bottom: 8,
                                                left: 10,
                                                right: 8),
                                            child: Text(
                                              'View Details',
                                              textDirection: TextDirection.ltr,
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 15.0,
                                                decoration: TextDecoration.none,
                                                fontWeight: FontWeight.normal,
                                              ),
                                            ),
                                          ),
                                          color: Colors.blueGrey,
                                          shape: new RoundedRectangleBorder(
                                              borderRadius:
                                                  new BorderRadius.circular(
                                                      20.0)),
                                          onPressed: () 
                                            Navigator.push(
                                                context,
                                                new MaterialPageRoute(
                                                    builder: (context) =>
                                                        detailsPage(value : anchors[i]['Oid'])));
                                          ,
                                        ),
                                ),

                                /////////// End of Buttons /////////////
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                )
          ],
        ),
      ),
    );
  


详情页:




import 'package:flutter/material.dart';

class detailsPage extends StatefulWidget 
  List value;
  detailsPage(Key key, @required this.value) : super(key: key);
  @override
  _detailsPageState createState() => _detailsPageState(value);


class _detailsPageState extends State<detailsPage> 
  List value;
  _detailsPageState(this.value);
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text("Anchors Details Page"),
        iconTheme: IconThemeData(color: Colors.white),
        backgroundColor: Colors.green,
      ),
      
      body: Container(
        child: ListView(
          children: <Widget>[
            Text(value[1]['Name']),
            Text(value[1]['Oid'].toString()),
            ListView.builder(
                shrinkWrap: true,
                itemCount: value[1]['DistributionCentres'].length,
                //context:context, //it saying the name parameter context is not defined
                physics: NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int i) 
                  return Text(value[1]['DistributionCentres'][i]['Name']);
                )
          ],
        ),
      ),
    );
  



我想在下面实现的图像:

【问题讨论】:

【参考方案1】:

第一个屏幕 onPressed 获取索引并将其分配给变量,或者您也可以传递 i 变量,

     onPressed: () 
         Navigator.push(context,new MaterialPageRoute(builder: (context) =>
              detailsPage(i))); ,

在详细页面

    class detailsPage extends StatefulWidget 
        final int selectedIndex;
        detailsPage(this.selectedIndex,Key key) : super(key: key);

       @override
        _detailsPageState createState() => _detailsPageState();
       

你要使用上一页的地方通过了索引,

    return Text(value[widget.selectedIndex]['DistributionCentres'][i]['Name']);

希望这会有所帮助..

【讨论】:

value 来自哪里?你只传递一个索引作为参数......不知道你从哪里得到 json 来使用那个索引。【参考方案2】:

问题似乎在这里

detailsPage(value : anchors[i]['Oid'])

您将Oid 作为Int 的参数传递。但是看看detailsPage的构造函数

List value;
detailsPage(Key key, @required this.value) : super(key: key);

参数valueList。我很难知道你想要做什么......但你需要修复这种类型不匹配。

编辑

看来value参数的类型应该是Map&lt;String,dynamic&gt;

class detailsPage extends StatefulWidget 
    Map<String, dynamic> value;
    
    detailsPage(Key key, @required this.value) : super(key: key);

    @override
    _detailsPageState createState() => _detailsPageState(value);


class _detailsPageState extends State<detailsPage> 
    Map<String, dynamic> value;
    
    _detailsPageState(this.value);

    @override
    Widget build(BuildContext context) 
        return Scaffold(
            appBar: AppBar(
                title: Text("Anchors Details Page"),
                iconTheme: IconThemeData(color: Colors.white),
                backgroundColor: Colors.green,
            ),            
            body: Container(
                child: ListView(
                children: <Widget>[
                    Text(value['Name']),
                    Text(value['Oid'].toString()),
                    ListView.builder(
                        shrinkWrap: true,
                        itemCount: value['DistributionCentres'].length,
                        //context:context, //it saying the name parameter context is not defined
                        physics: NeverScrollableScrollPhysics(),
                        itemBuilder: (BuildContext context, int i) 
                        return Text(value['DistributionCentres'][i]['Name']);
                        )
                ],
                ),
            ),
        );
    

然后你应该这样做

detailsPage(value : anchors[i])));

【讨论】:

好的,你能看看上面的图片吗?这就是我想要实现的目标 更新了我的答案@jonahrimsy 老实说,我无法用言语表达我的感激之情。非常感谢。您的解决方案运行良好。

以上是关于如何在详细屏幕中查看项目的详细信息 - Flutter的主要内容,如果未能解决你的问题,请参考以下文章

扑动 Firebase 动画列表视图如何将数据传递到详细信息屏幕

如何在javascript中检索数组内的数组?

过渡动画无法从回收视图到详细信息屏幕

如何查看特定列表视图项的详细数据

如何查看例外的详细信息

如何使用 Gunicorn 查看 Django 错误的详细信息?