android 如何从Django Rest API在Flutter应用中显示图像?

xdnvmnnf  于 2023-05-27  发布在  Android
关注(0)|答案(2)|浏览(117)

我在显示图像时遇到了问题,这些图像保存在Django Rest API的数据库中。这是我的API的postman输出:

[
    {
        "id": 1,
        "name": "firstshow",
        "image": "/media/images/firstshow.jpg"
    },
    {
        "id": 2,
        "name": "secondshow",
        "image": "/media/images/secondshow.jpg"
    },
    {
        "id": 3,
        "name": "thirdshow",
        "image": "/media/images/thirdshow.jpg"
    }
]

这是我的模型:

class ShowsModel{
  int? id;
  String? name;
  String? image;
  ShowsModel({this.id, this.name, this.image});
   ShowsModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    image = json['image'];
  }

  static List<ShowsModel> showsFromSnapshot(List showsSnapshot) {
    return showsSnapshot.map((data) {
      return ShowsModel.fromJson(data);
    }).toList();
  }
}

我已经创建了促销卡小部件,这需要imageUrl。我的主页使用promocard滑块部件,返回3个promocards。

class PromoCardSlider extends StatelessWidget {
  const PromoCardSlider({Key? key, required this.showsList}) : super(key: key);
  final List<ShowsModel> showsList;
  @override
  Widget build(BuildContext context) {
    return Container(
        height: 200,
        child: ListView.builder(
            itemCount: 3,
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            itemBuilder: (ctx, index) {
              return  promoCard(
                imageUrl: showsList[index].image![0]);
           
            }));
  }
}

在这一行imageUrl: showsList[index].image![0]);我得到错误:Exception has occurred. RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)
我该怎么解决?

xpcnnkqh

xpcnnkqh1#

用这个更新你的代码

class PromoCardSlider extends StatelessWidget {
  const PromoCardSlider({Key? key, required this.showsList}) : super(key: key);
  final List<ShowsModel> showsList;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: ListView.builder(
        itemCount: showsList.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (ctx, index) {
          return promoCard(imageUrl:"Set your base URl" showsList[index].image);
        },
      ),
    );
  }
}
q3qa4bjr

q3qa4bjr2#

出现此错误:图像字符串中索引0([0])处的字符,在这种情况下无效。
按照以下代码执行:

class PromoCardSlider extends StatelessWidget {
  const PromoCardSlider({Key? key, required this.showsList}) : super(key: key);
  final List<ShowsModel> showsList;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      child: ListView.builder(
        itemCount: showsList.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemBuilder: (ctx, index) {
          return Image.network(showsList[index].image!);
        },
      ),
    );
  }
}

相关问题