如何在 Flutter 中的轮播(滑块)中显示 JSON 文件中的图像

How do I display images from a JSON file in a carousel(slider) in Flutter

我有一个本地 json 文件 assets/properties.json,其中键 "image" 与其他键以及名称、地点等一起存储了 [5 个不同的图像]。我想要这个图片显示在 carouselSlider 中。

我进行了搜索,但找不到与我正在尝试做的事情相关的内容。

import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter_test_app/test_page.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'dart:async';
import 'package:flutter_test_app/propery_details_widget.dart';

class PropertyDetails extends StatefulWidget {
  @override
  _PropertyDetailsState createState() => _PropertyDetailsState();
}

class _PropertyDetailsState extends State<PropertyDetails> {
  List properties;
  Future<String> loadJsonData() async {
    var jsonText = await rootBundle.loadString("assets/properties.json");
    setState(() {
      properties = json.decode(jsonText);
    });
    return 'success';
  }
  int index = 1;

  List<String> listaTela = new List();

  CarouselSlider instance;

  @override
  void initState() {
    super.initState();
    this.loadJsonData();

    listaTela.add("assets/images/houses/house.jpg");
    listaTela.add('assets/images/houses/house1.jpg');
    listaTela.add('assets/images/houses/house2.jpg');
    listaTela.add('assets/images/houses/house3.jpg');
    listaTela.add('assets/images/houses/house4.jpg');
  }

  @override
  Widget build(BuildContext context) {
    instance = new CarouselSlider(
      autoPlay: true,
      autoPlayDuration: new Duration(seconds: 2),
      items: listaTela.map((it) {
        return new Container(
          width: MediaQuery.of(context).size.width,
//          margin: new EdgeInsets.symmetric(horizontal: 5.0),
          decoration: new BoxDecoration(

//            color: Colors.amber,
          ),
          child: new Image.asset(it),
        );
      }).toList(),
      height: 200,
    );

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Test App"),
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: <Widget>[
            instance,
            Flexible(
              fit: FlexFit.tight,
              child: Container(
                child: Details(),
              ),
            )
          ],
        ),
      ),
    );
  }
}

我不想像这样从 assests listaTela.add("assets/images/houses/house.jpg"); 调用图像,而是想从 JSON 文件中的 "image" 键调用它们。在我的 Carousel 之外,我可以通过 properties[index]["image"][0],

调用我的图片

据我了解你的问题,有几个挑战。

  1. 您可能想将 JSON 映射到 Dart 对象
  2. 您想在滑块中显示一组从索引开始的图像
  3. 当你想更新滑块时更新你的小部件树的机制

JSON 和 Dart

需要一些时间来适应构建 package:built_value 是一个不错的方法。它将允许您从 JSON 文件映射 Dart 对象或对象列表。或者,如果您想变得更简单,可以执行此处描述的操作:https://flutter.dev/docs/development/data-and-backend/json#serializing-json-manually-using-dartconvert

图片来自索引和更新

基本上,您想在 initState 中做的是:

load image data from json -> set start index -> somehow get Flutter to map N image paths to Image widgets and update tree

initState 这样的 pseudo-code 可能看起来像这样:

void initState() {
  super.initState();

  // step 1: load json and map it to Dart objects
  this.loadFromJson().then(() {
    // loadFromJson returns with a Future, `then` allows you to do computation after it returns
    setState(() {
      // setting property in setState tells Flutter: hey buddy, stuff happened, rebuild!
      this.startIndex = 0;
    });
  });
}

在您的构建中:

// [...]
CarouselSlider(
  items: listaTela.skip(this.startIndex).take(5).map((imgObj) => Image.asset(imgObj.assetPath))
);

希望我理解你的问题并给了你相关的答案。

试试这个。 (map 有可能无法工作,因为它的类型有误。我不认为你包含了整个 json,因为你是通过 index 对其进行索引的,但是您没有显示 json 周围的 [] 表示 json 数组。)

class _PropertyDetailsState extends State<PropertyDetails> {
  List properties;
  int index = 1;

  Future<void> loadJsonData() async {
    var jsonText = await rootBundle.loadString("assets/properties.json");
    setState(() {
      properties = json.decode(jsonText);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    Widget carousel = properties == null
        ? CircularProgressIndicator()
        : CarouselSlider(
            items: properties[index]["image"].map((it) {
              return new Container(
                width: MediaQuery.of(context).size.width,
                decoration: new BoxDecoration(),
                child: new Image.asset(it),
              );
            }).toList(),
            autoPlay: true,
            autoPlayDuration: new Duration(seconds: 2),
            height: 200,
          );

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Test App"),
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: <Widget>[
            carousel,
            Flexible(
              fit: FlexFit.tight,
              child: Container(
                child: Details(),
              ),
            )
          ],
        ),
      ),
    );
  }
}