【问题标题】:pase two json arrays inside flutter在颤振中插入两个 json 数组
【发布时间】:2021-01-27 18:56:51
【问题描述】:

你好,我是新手,正在尝试使用 mysql db 构建一个颤振应用程序,问题是我有一个带有两个对象的 json 响应,我想将其解析为一个小部件,我真的不知道如何制作他们的类谁能帮帮我:

Json 响应:

{
   "folders":[
      {
         "id":2531,
         "name":"MiniOSCE Ihsan",
         "img":null,
         "haschild":0,
         "parentid":1665,
         "createdate":"2019-11-26 12:21:27",
         "inarchive":0,
         "active":1
      }
   ],
   "files":[
      {
         "id":3669,
         "name":"Dermatology_Atlas.pdf 16.61MB",
         "img":null,
         "uploader":"admin",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/130620190Dermatology_Atlas.pdf",
         "createdate":"2019-06-13
23:54:41",
         "approved":0,
         "active":1
      },
      {
         "id":3670,
         "name":"Derma-\u062a\u0644\u062e\u064a\u0635.docx 27.88KB",
         "img":null,
         "uploader":"admin",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/130620190Derma-\u062a\u0644\u062e\u064a\u0635.docx",
         "createdate":"2019-06-13
23:54:41",
         "approved":0,
         "active":1
      },
      {
         "id":3671,
         "name":"ABC Dermatology and MiniOsce .pptx 67.43MB",
         "img":null,
         "uploader":"admin",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/130620190ABC Dermatology and MiniOsce .pptx",
         "createdate":"2019-06-13 23:54:41",
         "approved":0,
         "active":1
      },
      {
         "id":3672,
         "name":"Derma
1ry & 2ry skin lesions.pptx 2.02MB",
         "img":null,
         "uploader":"admin",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/130620190Derma 1ry & 2ry skin lesions.pptx",
         "createdate":"2019-06-13 23:54:41",
         "approved":0,
         "active":1
      },
      {
         "id":3673,
         "name":"Derma mini OSCE.docx
1.96MB",
         "img":null,
         "uploader":"admin",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/130620190Derma mini OSCE.docx",
         "createdate":"2019-06-13 23:54:41",
         "approved":0,
         "active":1
      },
      {
         "id":4955,
         "name":"immune 9 (8_9.3).m4a 45.66MB",
         "img":null,
         "uploader":"uploader18",
         "url":"http:\/\/msc-mu.com\/..\/uploaded\/231020190immune
9 (8_9.3).m4a",
         "createdate":"2019-10-23 12:01:36",
         "approved":0,
         "active":1
      }
   ]
}

我确实单独实现了文件夹列表和单独的文件如何做到这两个?并将它们转换为小部件

这是我的文件小部件代码!以及文件夹的一些更改:

class ListViewFolders extends StatelessWidget {
  final List<Files> filesSubject;
  ListViewFolders(this.filesSubject);
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int currentIndex) {
        return createFellowFolders(filesSubject[currentIndex], context);
      },
      itemCount: filesSubject.length,
    );
  }

  Widget createFellowFolders(Files files, BuildContext context) {
    String url = files.url;
    return Slidable(
      actionPane: SlidableDrawerActionPane(),
      actionExtentRatio: 0.25,
      child: Container(
        decoration: BoxDecoration(
            border: Border.all(width: 1), color: Colors.transparent.withOpacity(0.3)),
        child: ListTile(
          title: Text(
            files.name,
            style: TextStyle(color: Colors.white),
          ),
          subtitle: Text('Slide To View options',
              style: TextStyle(color: Colors.white)),
        ),
      ),
      actions: <Widget>[
        IconSlideAction(
          caption: 'Play',
          color: Colors.red,
          icon: FontAwesomeIcons.play,
          onTap: () {
            toast('coming soon');
          }
        ),
      ],
      secondaryActions: <Widget>[
        IconSlideAction(
          caption: 'Download',
          color: Colors.green,
          icon: Icons.arrow_circle_down,
          onTap: () async {
            final status = await Permission.storage.request();
            if (status.isGranted) {
              final externalDir = await getExternalStorageDirectory();
              final id = await FlutterDownloader.enqueue(
                  url: files.url,
                  savedDir: externalDir.path,
                  showNotification: true,
                  openFileFromNotification: true);
            } else {
              toast('Permission Denied');
            }
          },
        ),
        IconSlideAction(
          caption: 'Share',
          color: Colors.indigo,
          icon: Icons.share,
          onTap: () {
            Share.share(url);
          },
        ),
      ],
    );
  }
}

模型类:

import 'dart:core';

class YearsMain {
  final String id;
  final String name;


  const YearsMain({this.id, this.name});

  factory YearsMain.fromJson(Map<String, dynamic> jsonData) {
    return YearsMain(
      id: jsonData['id'].toString(),
      name: jsonData['name'],
    );
  }
}



class Folders {
   String id;
   String name;
   String haschild;
  Folders({this.id, this.name,this.haschild});

  factory Folders.fromJson(Map<String, dynamic> json)=> Folders(id: json["id"].toString(),name: json["name"],haschild: json["haschild"].toString());
}
class Files{
  String id ;
  String name ;
  String url ;
  Files({this.id,this.name,this.url});
  factory Files.fromJson(Map<String, dynamic> json)=> Files(id: json["id"].toString(),name: json["name"],url: json["url"]);

}

【问题讨论】:

  • 你能添加你的小部件代码吗?
  • 我已经添加了以及如何访问共享类中的文件夹和文件组件

标签: json flutter dart


【解决方案1】:

创建一个抽象类 Entity 并使 File 和 Folder 从它扩展。实体可以包含文件和文件夹共有的所有属性,例如 id 和 name。

abstract class Entity {
  String id;
  String name;
  
  Entity({String this.id, String this.name});
}

class Folder extends Entity {
    String haschild;
    Folder({ String id, String name, this.haschild }) : super(id: id, name: name);

    factory Folder.fromJson(Map<String, dynamic> json) => Folder(haschild: json["haschild"].toString(), id: json['id'].toString(), name: json['name'].toString());
}

class File extends Entity {
    String url;
    File({ String id, String name, this.url }) : super(id: id, name: name);
  
    factory File.fromJson(Map<String, dynamic> json)=> File(id: json["id"].toString(), name: json["name"].toString(), url: json["url"].toString());
}

创建一个列表而不是单独的列表。它可以同时包含文件和文件夹模型,因为它们从实体扩展而来,现在您拥有一个包含这两种类型的列表。

var data = jsonDecode(yourJson);

List<Entity> all = <Entity>[];
  
List folders = data["folders"].toList();
List files = data["files"].toList();
  
List<Folder> folders_model = folders.map((e) => Folder.fromJson(e)).toList();
List<File> files_model = files.map((e) => File.fromJson(e)).toList();

all.addAll(folders_model);
all.addAll(files_model);

像这样构建你的小部件

itemCount: all.length,
itemBuilder: (BuildContext context, int currentIndex) {
    Entity e = all[currentIndex];
    if(e is File) {
        File f = e;
        // Create and return your widget for file // You can access all the props of your file model
    } else if(e is Folder) {
        Folder f = e;
        // Create and return your widget for folder // You can access all the props of your folder model
    }
}

编辑 =======

这是 dartpad 中的最小代码:Code

【讨论】:

  • 第二个代码我应该把它放在我未来的函数中吗?
  • 在您的第三个代码中是否返回所有文件和文件夹?
  • 第二个代码是您将如何获取模型列表。如果你从服务器获取,你可以使用 Future 来分配列表
  • 第三个代码只是小部件构建部分。我刚刚将 List filesSubject 替换为 List all;现在在这个列表中,你有文件和文件夹,第三个代码显示了如何区分它们。
  • 最终,您只有一个包含文件和文件夹的列表以及一种区分它们的方法。因此,您可以轻松地仅创建一个列表视图,其子项基于您要分别对文件和文件夹执行的操作。
【解决方案2】:
var json = jsonDecode(your example);
json['files'].forEach((e){
   debugPrint(e['name']);
});

文件夹相同

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2021-03-21
    • 1970-01-01
    • 2020-02-26
    • 2020-06-26
    • 2023-03-21
    • 2021-10-27
    • 2022-01-05
    • 2021-06-24
    相关资源
    最近更新 更多