【发布时间】:2021-05-29 17:46:10
【问题描述】:
我正在尝试在我的 Django 网站上的颤振应用程序中显示图像。djangoApi 但我颤抖的问题是我看不到我的照片。 (我不知道是我的 Django 还是 Flutter 应用中的问题)
Flutter 应用:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response =
await client.get('https://pure-eyrie-09235.herokuapp.com/photoAPI');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
class Photo {
final int id;
final String title;
final String imageUrl;
final String desc;
Photo({this.id, this.title, this.imageUrl, this.desc});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
// albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
imageUrl: json['image'] as String,
desc: json['desc'] as String,
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'My Photo Sharing!';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title,),
centerTitle: true,
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(photos: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
),
itemCount: photos.length,
itemBuilder: (context, index){
return Image.network(
photos[index].imageUrl,
fit: BoxFit.cover,
height: 60.0, width: 60.0);
},
);
}
}
注意:如果我制作自己的应用程序,我只是想了解如何从 API 中完善
提前谢谢你。
【问题讨论】: