Flutter & Dart:如何从 Json 列表中取出 5 个 url 字符串到一个数组中

SangYeon

我正在编程,我有以下问题。我试图从以下 Json 中仅检索 5~6 个 thumnailUrls 作为字符串数组。

但是,我花了整整一周的时间来弄清楚,但我无法让它发挥作用。也许我找到了它,但没有正确理解它。

这是我的数据模型代码

class TestData {
  int albumId;
  int id;
  String title;
  String url;
  String thumbnailUrl;

  TestData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  TestData.fromJson(Map<String, dynamic> json) {
    albumId = json['albumId'];
    id = json['id'];
    title = json['title'];
    url = json['url'];
    thumbnailUrl = json['thumbnailUrl'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['albumId'] = this.albumId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['url'] = this.url;
    data['thumbnailUrl'] = this.thumbnailUrl;
    return data;
  }

}

这是我的主要

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:carlousel_test/model.dart';

Future<List<TestData>> fetchBanner(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/photos');

  return compute(parseBanner, response.body);
  //  return response.body;
}

List<TestData> parseBanner(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<TestData>((json) => TestData.fromJson(json)).toList();
}

//// you can ignore this part 
final List<String> testList = [];

List<String> countBanner(List<TestData> countBanner) {
  int count = countBanner.length;
  if (count > 5) count = 5;

  for (int i = 0; i < count; ++i) {
    testList.add(countBanner.elementAt(i).thumbnailUrl);
  }

  return testList;
}
///// til here cause i don't even know what i am doing here.


final List<String> imgList = [
  'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
  'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1523205771623-e0faa4d2813d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=89719a0d55dd05e2deae4120227e6efc&auto=format&fit=crop&w=1953&q=80',
  'https://images.unsplash.com/photo-1508704019882-f9cf40e475b4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c6e5e3aba713b17aa1fe71ab4f0ae5b&auto=format&fit=crop&w=1352&q=80',
  'https://images.unsplash.com/photo-1519985176271-adb1088fa94c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80'
];

final Widget placeholder = Container(color: Colors.grey);

final List child = map<Widget>(
  imgList,
  (index, i) {
    return Container(
      margin: EdgeInsets.all(5.0),
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        child: Stack(children: <Widget>[
          Image.network(i, fit: BoxFit.cover, width: 1000.0),
          Positioned(
            bottom: 0.0,
            left: 0.0,
            right: 0.0,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color.fromARGB(200, 0, 0, 0),
                    Color.fromARGB(0, 0, 0, 0)
                  ],
                  begin: Alignment.bottomCenter,
                  end: Alignment.topCenter,
                ),
              ),
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
              child: Text(
                'No. $index image',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ]),
      ),
    );
  },
).toList();

List<T> map<T>(List list, Function handler) {
  List<T> result = [];
  for (var i = 0; i < list.length; i++) {
    result.add(handler(i, list[i]));
  }

  return result;
}

class CarouselWithIndicator extends StatefulWidget {
  @override
  _CarouselWithIndicatorState createState() => _CarouselWithIndicatorState();
}

class _CarouselWithIndicatorState extends State<CarouselWithIndicator> {
  int _current = 0;

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      CarouselSlider(
        items: child,
        autoPlay: true,
        enlargeCenterPage: true,
        aspectRatio: 2.0,
        onPageChanged: (index) {
          setState(() {
            _current = index;
          });
        },
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: map<Widget>(
          imgList,
          (index, url) {
            return Container(
              width: 8.0,
              height: 8.0,
              margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index
                      ? Color.fromRGBO(0, 0, 0, 0.9)
                      : Color.fromRGBO(0, 0, 0, 0.4)),
            );
          },
        ),
      ),
    ]);
  }
}

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

class MyApp extends StatefulWidget {
//  List<TestData> banners;

  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Carousel Slider',
      theme: ThemeData(primarySwatch: Colors.teal),
      home: Scaffold(
        appBar: AppBar(title: Text('Carousel Demo')),
        body: ListView(
          children: <Widget>[
            Padding(
                padding: EdgeInsets.symmetric(vertical: 15.0),
                child: Column(children: [
                  Text('Carousel With Indecator'),
                  CarouselWithIndicator(),
                ])),
            Padding(
              padding: EdgeInsets.all(0.0),
              child: FutureBuilder<List<TestData>>(
                future: fetchBanner(http.Client()),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return CarouselSlider(
                        autoPlay: false,
                        height: 300.0,
                        aspectRatio: 16 / 9,
                        initialPage: 0,
                        viewportFraction: 1.0,
                        enableInfiniteScroll: true,
                        scrollDirection: Axis.horizontal,
                        items: snapshot.data.map((i) {
                          return Builder(builder: (BuildContext context) {
                            return Container(
                              width: MediaQuery.of(context).size.width,
                              margin: EdgeInsets.symmetric(horizontal: 0.0),
                              decoration: BoxDecoration(color: Colors.white),
                              child: Image.network(i.thumbnailUrl,
                                  fit: BoxFit.fill),
                            );
                          });
                        }).toList());
                  }
                  return CircularProgressIndicator();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

正如你看到的代码,我喜欢用来自互联网的 Json(来自 TestData 的 testList)替换以下(imglist)。

final List<String> imgList = [
  'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
  'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1523205771623-e0faa4d2813d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=89719a0d55dd05e2deae4120227e6efc&auto=format&fit=crop&w=1953&q=80',
  'https://images.unsplash.com/photo-1508704019882-f9cf40e475b4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c6e5e3aba713b17aa1fe71ab4f0ae5b&auto=format&fit=crop&w=1352&q=80',
  'https://images.unsplash.com/photo-1519985176271-adb1088fa94c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80'
];

我看过很多文章,但由于我缺乏基本知识,找不到适合我的东西。先谢谢了~!

奥比汗

修复了您的代码(只是fetchBanner功能)并删除了该parseBanner功能。我特意将更改保持在最低限度,以便您的大部分代码保持完整。

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'dart:convert';

class TestData {
  int albumId;
  int id;
  String title;
  String url;
  String thumbnailUrl;

  TestData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  TestData.fromJson(Map<String, dynamic> json) {
    albumId = json['albumId'];
    id = json['id'];
    title = json['title'];
    url = json['url'];
    thumbnailUrl = json['thumbnailUrl'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['albumId'] = this.albumId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['url'] = this.url;
    data['thumbnailUrl'] = this.thumbnailUrl;
    return data;
  }
}

Future<List<TestData>> fetchBanner(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/photos');

  List images = json.decode(response.body);
  var data = images.map((image) => TestData.fromJson(image)).toList();

  return data;
}

//// you can ignore this part 
final List<String> testList = [];

List<String> countBanner(List<TestData> countBanner) {
  int count = countBanner.length;
  if (count > 5) count = 5;

  for (int i = 0; i < count; ++i) {
    testList.add(countBanner.elementAt(i).thumbnailUrl);
  }

  return testList;
}
///// til here cause i don't even know what i am doing here.


final List<String> imgList = [
  'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
  'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
  'https://images.unsplash.com/photo-1523205771623-e0faa4d2813d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=89719a0d55dd05e2deae4120227e6efc&auto=format&fit=crop&w=1953&q=80',
  'https://images.unsplash.com/photo-1508704019882-f9cf40e475b4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c6e5e3aba713b17aa1fe71ab4f0ae5b&auto=format&fit=crop&w=1352&q=80',
  'https://images.unsplash.com/photo-1519985176271-adb1088fa94c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80'
];

final Widget placeholder = Container(color: Colors.grey);

final List child = map<Widget>(
  imgList,
  (index, i) {
    return Container(
      margin: EdgeInsets.all(5.0),
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
        child: Stack(children: <Widget>[
          Image.network(i, fit: BoxFit.cover, width: 1000.0),
          Positioned(
            bottom: 0.0,
            left: 0.0,
            right: 0.0,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color.fromARGB(200, 0, 0, 0),
                    Color.fromARGB(0, 0, 0, 0)
                  ],
                  begin: Alignment.bottomCenter,
                  end: Alignment.topCenter,
                ),
              ),
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
              child: Text(
                'No. $index image',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ]),
      ),
    );
  },
).toList();

List<T> map<T>(List list, Function handler) {
  List<T> result = [];
  for (var i = 0; i < list.length; i++) {
    result.add(handler(i, list[i]));
  }

  return result;
}

class CarouselWithIndicator extends StatefulWidget {
  @override
  _CarouselWithIndicatorState createState() => _CarouselWithIndicatorState();
}

class _CarouselWithIndicatorState extends State<CarouselWithIndicator> {
  int _current = 0;

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      CarouselSlider(
        items: child,
        autoPlay: true,
        enlargeCenterPage: true,
        aspectRatio: 2.0,
        onPageChanged: (index) {
          setState(() {
            _current = index;
          });
        },
      ),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: map<Widget>(
          imgList,
          (index, url) {
            return Container(
              width: 8.0,
              height: 8.0,
              margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _current == index
                      ? Color.fromRGBO(0, 0, 0, 0.9)
                      : Color.fromRGBO(0, 0, 0, 0.4)),
            );
          },
        ),
      ),
    ]);
  }
}

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

class MyApp extends StatefulWidget {
//  List<TestData> banners;

  MyApp({Key key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Carousel Slider',
      theme: ThemeData(primarySwatch: Colors.teal),
      home: Scaffold(
        appBar: AppBar(title: Text('Carousel Demo')),
        body: ListView(
          children: <Widget>[
            Padding(
                padding: EdgeInsets.symmetric(vertical: 15.0),
                child: Column(children: [
                  Text('Carousel With Indecator'),
                  CarouselWithIndicator(),
                ])),
            Padding(
              padding: EdgeInsets.all(0.0),
              child: FutureBuilder<List<TestData>>(
                future: fetchBanner(http.Client()),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return CarouselSlider(
                        autoPlay: false,
                        height: 300.0,
                        aspectRatio: 16 / 9,
                        initialPage: 0,
                        viewportFraction: 1.0,
                        enableInfiniteScroll: true,
                        scrollDirection: Axis.horizontal,
                        items: snapshot.data.map((i) {
                          return Builder(builder: (BuildContext context) {
                            return Container(
                              width: MediaQuery.of(context).size.width,
                              margin: EdgeInsets.symmetric(horizontal: 0.0),
                              decoration: BoxDecoration(color: Colors.white),
                              child: Image.network(i.thumbnailUrl,
                                  fit: BoxFit.fill),
                            );
                          });
                        }).toList());
                  }
                  return CircularProgressIndicator();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何从列表中取出字符串并一次比较一个字符

来自分类Dev

Swift:如何在 plist 中获取第一个数组字符串?

来自分类Dev

如何从10个字符串的数组中打印5个唯一的字符串

来自分类Dev

如何从另一个数组中找到的一个数组中增加每个字符串元素?

来自分类Dev

如何将字符串拆分为一个数组,我想将其推入另一个数组中

来自分类Dev

如何将一个字符串数组存储到另一个字符串数组中?

来自分类Dev

Flutter Dart将字符串从另一个列表转换为列表

来自分类Dev

如何根据包含在另一个数组中的字符串在NSArray中查找匹配的字典

来自分类Dev

如何在gwt中的字符串中创建一个URL

来自分类Dev

如何从Lua的字符串中仅取出一个单词

来自分类Dev

如何从Lua的字符串中仅取出一个单词

来自分类Dev

将JSON加载到BigQuery中:字段有时是一个数组,有时是一个字符串

来自分类Dev

如何以列表中的单独字符串而不是一个大列表的形式读取JSON文件

来自分类Dev

从JSON对象数组文件中创建一个新的JSON字符串-不包含不包含img URL的对象

来自分类Dev

如何在JSON文件中查找字符串,然后在列表中获取下一个?

来自分类Dev

如何在JSON文件中查找字符串,然后在列表中获取下一个?

来自分类Dev

如何 preg_match() 一个字符串并将所有结果输出到一个数组中?

来自分类Dev

如何在数组数组中连接数组的字符串属性并在每个数组中创建一个新属性

来自分类Dev

如何在json字符串java中的数字之间给一个空格?

来自分类Dev

如何在一个JsonArray中添加许多json字符串?

来自分类Dev

如何在一个JsonArray中添加许多json字符串?

来自分类Dev

如何根据反应本机中的条件从json字符串中选择一个对象

来自分类Dev

如何从字符串数组列表中删除一个字符串,ANDROID

来自分类Dev

如何从字符串数组列表中删除一个字符串,ANDROID

来自分类Dev

如何在C#中从字符串中挑选一个数字

来自分类Dev

将字符串数组复制到C中的另一个数组中

来自分类Dev

无法从一组字符串中取出一个数字-C

来自分类Dev

如何在每5个字之后将<br>标签放在一个长字符串中?

来自分类Dev

在Ruby中,如果数组字符串等于第二个数组字符串中的任何一个,那么如何从文件或数组中删除?

Related 相关文章

  1. 1

    如何从列表中取出字符串并一次比较一个字符

  2. 2

    Swift:如何在 plist 中获取第一个数组字符串?

  3. 3

    如何从10个字符串的数组中打印5个唯一的字符串

  4. 4

    如何从另一个数组中找到的一个数组中增加每个字符串元素?

  5. 5

    如何将字符串拆分为一个数组,我想将其推入另一个数组中

  6. 6

    如何将一个字符串数组存储到另一个字符串数组中?

  7. 7

    Flutter Dart将字符串从另一个列表转换为列表

  8. 8

    如何根据包含在另一个数组中的字符串在NSArray中查找匹配的字典

  9. 9

    如何在gwt中的字符串中创建一个URL

  10. 10

    如何从Lua的字符串中仅取出一个单词

  11. 11

    如何从Lua的字符串中仅取出一个单词

  12. 12

    将JSON加载到BigQuery中:字段有时是一个数组,有时是一个字符串

  13. 13

    如何以列表中的单独字符串而不是一个大列表的形式读取JSON文件

  14. 14

    从JSON对象数组文件中创建一个新的JSON字符串-不包含不包含img URL的对象

  15. 15

    如何在JSON文件中查找字符串,然后在列表中获取下一个?

  16. 16

    如何在JSON文件中查找字符串,然后在列表中获取下一个?

  17. 17

    如何 preg_match() 一个字符串并将所有结果输出到一个数组中?

  18. 18

    如何在数组数组中连接数组的字符串属性并在每个数组中创建一个新属性

  19. 19

    如何在json字符串java中的数字之间给一个空格?

  20. 20

    如何在一个JsonArray中添加许多json字符串?

  21. 21

    如何在一个JsonArray中添加许多json字符串?

  22. 22

    如何根据反应本机中的条件从json字符串中选择一个对象

  23. 23

    如何从字符串数组列表中删除一个字符串,ANDROID

  24. 24

    如何从字符串数组列表中删除一个字符串,ANDROID

  25. 25

    如何在C#中从字符串中挑选一个数字

  26. 26

    将字符串数组复制到C中的另一个数组中

  27. 27

    无法从一组字符串中取出一个数字-C

  28. 28

    如何在每5个字之后将<br>标签放在一个长字符串中?

  29. 29

    在Ruby中,如果数组字符串等于第二个数组字符串中的任何一个,那么如何从文件或数组中删除?

热门标签

归档