【问题标题】:Get Image from my Django application in flutter在颤振中从我的 Django 应用程序中获取图像
【发布时间】: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 中完善

提前谢谢你。

【问题讨论】:

    标签: python django api flutter


    【解决方案1】:

    首先,您在 Image.network 中犯了两个错误,应该是 photos[index].url 而不是 title,在 Photo.fromJson 中应该是 json['image'] 而不是 json['url'](我检查了你的 api)。

    这是一种无需 parsePhotos 即可替换您的 fetchPhotos 的工作方法(我摆脱了 http.Client ):

    Future<List<Photo>> fetchPhotos() async {
     http.Response res = await http.get('https://pure-eyrie-09235.herokuapp.com/photoAPI');
     var parsed = jsonDecode(res) ; 
     List<Photo> photos = [] ; 
     for (var photo in parsed) 
        photos.add(Photo.fromJson(photo)) ; 
     return photos ; 
    
    }
     
    

    【讨论】:

    • 我通过在 Photo 类中添加 ( desc: json['description'] as String, ) 解决了我的问题。另外,由于http请求和作为API的url的字符串输入之间的混淆,您编写的方法不起作用。所以最好是保持我的功能。谢谢你的时间。
    【解决方案2】:

    所以,答案应该是这样的:

    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['description'] as String,
        );
      }
    }
    

    并且在构建方法中应该返回 PhotosList 类:

        return Stack(
          fit: StackFit.passthrough,
          children: <Widget>[
            Image.network(photos[index].imageUrl,
              fit: BoxFit.fill,
              height: 60,
              width: 60,),
            Text(photos[index].title, style: TextStyle(color: Colors.white),),
          ],
        );
    

    之后一切都会好起来的。

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2019-04-25
      • 2019-08-01
      • 2019-02-01
      • 2020-12-28
      • 1970-01-01
      • 2020-05-06
      • 2021-10-13
      • 2021-04-24
      相关资源
      最近更新 更多