【问题标题】:Fetchinng Data from PHP REST API in flutter gives exception在颤振中从 PHP REST API 获取数据给出异常
【发布时间】:2021-11-03 18:17:07
【问题描述】:

创建了一个用于在 PHP MYSQL 中获取数据的 REST API。部分数据已提取,而其他图像未提取,并出现以下异常消息。

到 REST API 的链接是 https://gujapp.geekconnects.co/getdata.php

在任何网络上阻止应用 IP 一次使用后。我尝试过使用VPN,但一段时间后它也被阻止了。

======== Exception caught by image resource service ================================================
The following SocketException was thrown resolving an image codec:
OS Error: Connection reset by peer, errno = 104, address = gujapp.geekconnects.co, port = 59798

When the exception was thrown, this was the stack: 
Image provider: NetworkImage("https://gujapp.geekconnects.co/parentuploads/images2.png", scale: 1.0)
Image key: NetworkImage("https://gujapp.geekconnects.co/parentuploads/images2.png", scale: 1.0)
====================================================================================================

REST 服务的代码

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'album.dart';


class Services {
  static var url = Uri.parse("https://gujapp.geekconnects.co/getdata.php");
  static Future<List<Album>> getPhotos() async{
    try{
      final response = await http.get(url);
      if(response.statusCode==200)
      {
        List<Album> list=parsePhotos(response.body);
        return list;
      }
      else
      {
        throw Exception("Erroor");
      }
    }catch(e){
      throw new Exception(e.toString());
    }
  }

  static List<Album> parsePhotos(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<Album>((json)=>Album.fromJson(json)).toList();
  }

}

专辑.dart

class Album{
  String albumId;
  String id;
  String title;
  String url;
  String thumbnailUrl;

  Album({this.albumId,this.id,this.title,this.url,this.thumbnailUrl});

  factory Album.fromJson(Map<String,dynamic>json)
  {
    return Album(
      albumId: json['albumId'] as String,
      id: json['id'] as String,
      title: json['title'] as String,
      url: json['url'] as String,
      thumbnailUrl: json['thumbnailUrl'] as String,
    );
  }
}

gridcell.dart

import 'package:flutter/material.dart';
import 'album.dart';
import 'package:google_fonts/google_fonts.dart';

class AlbumCell extends StatelessWidget{
  const AlbumCell(this.album);
  @required
  final Album album;

  @override
  Widget build(BuildContext context) {
    return Card(
      shape:RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Container(
          alignment: Alignment.center,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Flexible(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10.0),
                  child: FadeInImage.assetNetwork(
                    placeholder: "images/no_image.png",
                    image: album.thumbnailUrl,
                    width: 100,
                    height: 100,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(4.0,10.0,4.0,10.0),
                child: Text(
                  album.title,
                  maxLines: 2,
                  softWrap: true,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.poppins(textStyle:TextStyle(fontSize: 13.0, fontWeight: FontWeight.w500)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: php android json flutter rest


    【解决方案1】:

    尝试更改您的数据类 - Album

    import 'dart:convert';
    
    class Album {
      String albumId;
      String id;
      String title;
      String url;
      String thumbnailUrl;
      
      Album({
        required this.albumId,
        required this.id,
        required this.title,
        required this.url,
        required this.thumbnailUrl,
      });
    
      Map<String, dynamic> toMap() {
        return {
          'albumId': albumId,
          'id': id,
          'title': title,
          'url': url,
          'thumbnailUrl': thumbnailUrl,
        };
      }
    
      factory Album.fromMap(Map<String, dynamic> map) {
        return Album(
          albumId: map['albumId'],
          id: map['id'],
          title: map['title'],
          url: map['url'],
          thumbnailUrl: map['thumbnailUrl'],
        );
      }
    
      String toJson() => json.encode(toMap());
    
      factory Album.fromJson(String source) => Album.fromMap(json.decode(source));
    }
    

    然后像这样转换数据

    Future<List<Album>> getAlbums() async {
    var url = Uri.parse("https://gujapp.geekconnects.co/getdata.php");
    
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        final maps = jsonDecode(response.body).cast<Map<String, dynamic>>();
    
        return List.generate(maps.length, (i) {
          return Album.fromMap(maps[i]);
        });
      } else {
        throw Exception("Erroor");
       }
     } catch (e) {
      throw new Exception(e.toString());
     }
    }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () async {
                var albums = await getAlbums();
              },
              child: Text("Run"),
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 仍然无法正常工作我认为这是我的托管服务提供商的问题。我正在使用共享主机 CPanel。
    • 如果不完整查看代码,就无法理解错误在哪里。从项目中完全删除所有图像,并尝试从远程服务器添加图像
    猜你喜欢
    • 2022-01-01
    • 2021-01-26
    • 2020-10-17
    • 2021-03-26
    • 2021-12-16
    • 2019-04-25
    • 2019-11-21
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多