在 Flutter 中向 CarouselSlider Widget 显示 JSON 数据

Posted

技术标签:

【中文标题】在 Flutter 中向 CarouselSlider Widget 显示 JSON 数据【英文标题】:Display JSON data to the CarouselSlider Widget in Flutter 【发布时间】:2020-02-11 00:41:37 【问题描述】:

我有这样的 Json 数据(执行 getdata.php 时):

["sponsorlogo":"/localhost/webview/img/logo01.jpg","sponsorlogo":"/localhost/webview/img/logo02.jpg","sponsorlogo":"/localhost/webview/img/logo03.jpg"]

我需要在 Flutter 中显示 CarouselSlider 小部件 (https://pub.dev/packages/carousel_slider) 的图像 url。遵循小部件部分到目前为止我正在尝试做的事情(仍未解决)。

class SponsorSlider extends StatefulWidget 
  @override
  _SponsorSliderState createState() => _SponsorSliderState();


class _SponsorSliderState extends State<SponsorSlider> 

  Future<List> getSponsorSlide() async 
    final response = await http.get("getdata.php");
    return json.decode(response.body);
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Container(
        child: Card(
          child: new FutureBuilder<List>(
            future: getSponsorSlide(),
            builder: (context, snapshot) 
              if (snapshot.hasError) print(snapshot.error);
              return snapshot.hasData
                  ? new SponsorList(
                      list: snapshot.data,
                    )
                  : new Center(
                      child: new CircularProgressIndicator()
                    );
            ,
          ),
        ),
      ),
    );
  


class SponsorList extends StatelessWidget 
  final List list;
  SponsorListSimple(this.list);
  int _current = 0;
  int index = 1;

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Column(
        children: <Widget>[
          CarouselSlider(
            height: 200.0,
            initialPage: 0,
            onPageChanged: (index) 
              setState(() 
                _current = index;
              );
            ,
            autoPlay: true,
            autoPlayInterval: Duration(seconds: 2),
            reverse: false,
            items: list[index]["sponsorlogo"].map((imageUrl)
              return Builder (
                builder: (BuildContext context)
                return Container(
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.symmetric(horizontal: 10.0),
                  decoration: BoxDecoration(
                    color: Colors.green,
                  ),
                  child: Image.network(
                    imageUrl,
                    fit:BoxFit.fill,
                  ),
                );
              );
            ).toList(),
          )
        ],
      ),
    );
  

我尝试获取“imageUrl”,然后将其放在“items”参数中,以便 json 文件中的 URL 列表将显示在轮播中。

【问题讨论】:

【参考方案1】:

您的原始代码中存在一些错误 第一步:解析带有payload类的json字符串,可以看代码sn -p 第二步:Image.network需要http://,php返回json不包含http:// 第 3 步:SponsorList 必须是 StatefulWidget,因为您使用 setState

用于解析json字符串和payload类的代码sn-p

// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

List<Payload> payloadFromJson(String str) => List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));

String payloadToJson(List<Payload> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Payload 
    String sponsorlogo;

    Payload(
        this.sponsorlogo,
    );

    factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        sponsorlogo: json["sponsorlogo"] == null ? null : json["sponsorlogo"],
    );

    Map<String, dynamic> toJson() => 
        "sponsorlogo": sponsorlogo == null ? null : sponsorlogo,
    ;

完整的工作代码

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

List<Payload> payloadFromJson(String str) => List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));

String payloadToJson(List<Payload> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Payload 
  String sponsorlogo;

  Payload(
    this.sponsorlogo,
  );

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
    sponsorlogo: json["sponsorlogo"] == null ? null : json["sponsorlogo"],
  );

  Map<String, dynamic> toJson() => 
    "sponsorlogo": sponsorlogo == null ? null : sponsorlogo,
  ;


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

class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: SponsorSlider(),
    );
  




class SponsorSlider extends StatefulWidget 
  @override
  _SponsorSliderState createState() => _SponsorSliderState();


class _SponsorSliderState extends State<SponsorSlider> 

  Future<List<Payload>> getSponsorSlide() async 
    //final response = await http.get("getdata.php");
    //return json.decode(response.body);
    String response = '["sponsorlogo":"https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80","sponsorlogo":"https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80","sponsorlogo":"https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80"]';
    var payloadList = payloadFromJson(response);
    return payloadList;
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Container(
        child: Card(
          child: new FutureBuilder<List<Payload>>(
            future: getSponsorSlide(),
            builder: (context, snapshot) 
              if (snapshot.hasError) print(snapshot.error);
              return snapshot.hasData
                  ? new SponsorList(
                list: snapshot.data,
              )
                  : new Center(
                  child: new CircularProgressIndicator()
              );
            ,
          ),
        ),
      ),
    );
  


class SponsorList extends StatefulWidget 
  final List<Payload> list;
  SponsorList(this.list);

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


class _SponsorListState extends State<SponsorList> 
  int _current = 0;

  int index = 1;

  @override
  Widget build(BuildContext context) 
    return Container(
      child: Column(
        children: <Widget>[
          CarouselSlider(
            height: 200.0,
            initialPage: 0,
            onPageChanged: (index) 
              setState(() 
                _current = index;
              );
            ,
            autoPlay: true,
            autoPlayInterval: Duration(seconds: 2),
            reverse: false,
            items: widget.list.map((imageUrl)
              return Builder (
                  builder: (BuildContext context)
                    return Container(
                      width: MediaQuery.of(context).size.width,
                      margin: EdgeInsets.symmetric(horizontal: 10.0),
                      decoration: BoxDecoration(
                        color: Colors.green,
                      ),
                      child: Image.network(
                        imageUrl.sponsorlogo,
                        fit:BoxFit.fill,
                      ),
                    );
                  );
            ).toList(),
          )
        ],
      ),
    );
  

【讨论】:

以上是关于在 Flutter 中向 CarouselSlider Widget 显示 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中向 SelectableText 添加“溢出”?

在 Flutter 中向 CarouselSlider Widget 显示 JSON 数据

如何在 Flutter 的 Firestore 中向数组中添加相等的元素?

在 setState() 方法中向 List 添加元素,而不是保存元素 Flutter

想要向新用户显示欢迎页面,并在 Flutter Firebase 中向登录用户显示主屏幕

如何在颤振中向 multiDexKeepFile 添加类?