flutter 这是我从API响应中得到的图片列表,我如何在UI中显示它?

webghufk  于 2023-01-18  发布在  Flutter
关注(0)|答案(4)|浏览(155)

考虑:

"data": [
    {
      "sno": 74,
      "userid": "rajesh@gmail.com",
      "postUrl": "[https://uat-marc.s3.ap-south-1.amazonaws.com/news-feed/74_0.jpg@ https://uat-marc.s3.ap-south-1.amazonaws.com/news-feed/74_1.jpg@ https://uat-marc.s3.ap-south-1.amazonaws.com/news-feed/74_2.jpg]",
      "contentType": "img"
    }
  ]

这是响应。我必须在UI中将“postUrl”图像显示为网络图像。我在该列表中只获得一个图像。我如何在滑块中显示所有图像?
我已经通过创建一个模型来完成了,一切都很好。但是我不能在UI上显示。

trnvg8h3

trnvg8h31#

您可以将postUrl作为字符串获取。希望您已经通过获取此响应完成了这些工作。
首先,必须从整个字符串中删除[]中的括号。
现在你可以把这个字符串按'@ '分割,这样你就可以得到3个URL,你可以一个接一个地显示它们。
下面介绍如何拆分字符串:

final postUrls = 'yourURLs';
final split = tagName.split('@ ');
final Map<int, String> values = {
  for (int i = 0; i < split.length; i++)
    i: split[i]
};
print(values);  // {0: url1, 1: url2, 2: url3}

final url1 = values[0];
final url2 = values[1];
final url3 = values[2];

print(url1);  // URL1
print(url2);  //  URL2
print(url3);  // URL3

试试看,如果你有任何问题,一定要告诉我。

8zzbczxx

8zzbczxx2#

请看这个小工具。
我已经创建了一个本地JSON文件,并使数据可用。请将这些本地文件读取替换为http调用。

class ImageBuilderSample extends StatefulWidget {
  const ImageBuilderSample({Key? key}) : super(key: key);

  @override
  State<ImageBuilderSample> createState() => _ImageBuilderSampleState();
}

class _ImageBuilderSampleState extends State<ImageBuilderSample> {
  List<String> _images = [];
  Future<void> readJson() async {
    final String response =
        await rootBundle.loadString('assets/json_data/sample.json');
    final data = await json.decode(response);
    //print(data['data'][0]['postUrl']);

    final List<String> split = data['data'][0]['postUrl'].split('@ ');
    print(split[2].substring(0, split[2].length - 1));
    setState(() {
      _images = split;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Image Builder Application",
        ),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              readJson();
            },
            child: Text(
              "Sample",
            ),
          ),
          _images.isNotEmpty
              ? ListView.builder(
                  shrinkWrap: true,
                  itemBuilder: (context, data) {
                    if (data == 0) {
                      return Image.network(
                        _images[data].substring(1),
                        height: 100,
                      );
                    }
                    if (data == _images.length - 1) {
                      return Image.network(
                        _images[data].substring(0, _images[data].length - 1),
                        height: 100,
                      );
                    }
                    return Image.network(
                      _images[data],
                      height: 100,
                    );
                  },
                  itemCount: _images.length,
                )
              : Container()
        ],
      ),
    );
  }
}
a0x5cqrl

a0x5cqrl3#

首先从API响应创建一个模型类,如下所示:

class Response {
  List<Data>? data;

  Response({this.data});

  Response.fromJson(Map<String, dynamic> json) {
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((v) {
        data!.add(new Data.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Data {
  int? sno;
  String? userid;
  String? postUrl;
  String? contentType;

  Data({this.sno, this.userid, this.postUrl, this.contentType});

  Data.fromJson(Map<String, dynamic> json) {
    sno = json['sno'];
    userid = json['userid'];
    postUrl = json['postUrl'];
    contentType = json['contentType'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['sno'] = this.sno;
    data['userid'] = this.userid;
    data['postUrl'] = this.postUrl;
    data['contentType'] = this.contentType;
    return data;
  }
}

然后创建一个有状态的小部件类:

class ImageExample extends StatefulWidget {
  const ImageExample({Key key}) : super(key: key);

  @override
  State<ImageExample> createState() => _ImageExampleState();
}

class _ImageExampleState extends State<ImageExample> {
  ImageResponse imageResponse;
  @override
  Widget build(BuildContext context) {
    return imageResponse != null
        ? ListView.builder(
            shrinkWrap: true,
            itemBuilder: (context, data) {
              List<String> image = imageResponse.data[data].postUrl
                  .trim()
                  .replaceAll("[", "")
                  .replaceAll("]", "")
                  .replaceAll(" ", "")
                  .split("@");
              return ListView.builder(
                  shrinkWrap: true,
                  itemCount: image.length,
                  itemBuilder: (context, index) {
                    return Image.network(
                      image[index],
                      height: 100,
                      width: 100,
                    );
                  });
            },
            itemCount: imageResponse.data.length,
          )
        : Container();
  }

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

  Future<void> apiCall() async {
    var response = await http.get(
        Uri.parse('api')); // you http api address
    setState(() {
      final body = json.decode(response.body);
      imageResponse = ImageResponse.fromJson(body);
    });
  }
}
7gcisfzg

7gcisfzg4#

请务必关注博客文章 How to read a JSON file in Flutter and display it in a listview 以供参考。
应遵循的步骤:
1.创建PODO类,将JSON数据反序列化为Dart对象和数据类型。
1.并使用提取的数据通过ListView.Builder小部件或您选择的任何小部件构建器构建UI。

相关问题