服务器关闭时如何在FutureBuilder中显示小部件?

时间:2020-06-06 05:31:17

标签: flutter

我正在尝试获取服务器上的映像,但是我正在模拟离线情况。因此,我无权访问服务器,因此决定使用FutureBuilder,因为否则我会收到类似于错误404的错误,并且我的应用程序死亡。

我收到此错误:

SocketException (SocketException: OS Error: Connection refused, errno = 111, address = 192.168.1.56, port = 59225)

在此图像中,您可以看到我无权访问服务器并且收到错误111,但我的应用程序死了。我想知道如何控制这种行为,并且要让我的应用程序继续运行,我想让我的小部件返回。

enter image description here

这是我的代码:

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

return FutureBuilder(
    future: http.get("http://192.168.1.56:3000/uploads/usuarios/523471653716.jpg"),
    builder: (BuildContext context, AsyncSnapshot<http.Response> snapshot) {
      //never enters in offline mode
      print(snapshot.error);

注意:我不知道这是否是最好的方法,我只是想避免在无法获取图像时杀死我的应用程序的错误,如下所示:

FadeInImage(
        width: 50,
        height: 50,
        image: NetworkImage("http://192.168.1.56:3000/uploads/usuarios/523471653716.jpg"), //mode offline crash my app
        placeholder: AssetImage('assets/img/gallery.png'),
        fadeInDuration: Duration(milliseconds: 500),
        fit: BoxFit.cover,
      ),

更新了我的代码:

  return FutureBuilder(
    future: http
 .get("http://192.168.1.56:3000/uploads/usuarios/523471653716.jpg"),
    builder: (BuildContext context, AsyncSnapshot<http.Response> snapshot) {
      if (snapshot.hasData) {
        if (snapshot.data.statusCode != 200) {
          return Text('Failed to load the image!');
        } else {
          return Image.memory(snapshot.data.bodyBytes);
        }
      } else if (snapshot.hasError) {
        return Text('Failed to make a request!');
      } else {
        return Text('Loading');
      }
    },
  );
}

1 个答案:

答案 0 :(得分:2)

AsyncSnapshot中作为builder的第二个参数提供的FutureBuilder具有两个属性来检查HTTP请求的结果:hasDatahasError 。如果请求成功,则hasData为true,您可以从data属性中获取实际数据。否则,将设置hasError,并且可以在error属性中访问错误。另外,当请求成功完成但导致输入的代码不是200时,您应该检查data.statusCode

因此,您需要在构建器中检查它们并返回适当的小部件:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.cyan,
      ),
      home: Scaffold(
        appBar: AppBar(title: Text('App')),
        body: Center(
          child: FutureBuilder(
            future: http.get(
                "https://upload.wikimedia.org/wikipedia/commons/c/c8/Strombus_sinuatus_2010_G1.jpg"),
            builder:
                (BuildContext context, AsyncSnapshot<http.Response> snapshot) {
              if (snapshot.hasData) {
                if (snapshot.data.statusCode != 200) {
                  return Text('Failed to load the image!');
                } else {
                  return Image.memory(snapshot.data.bodyBytes);
                }
              } else if (snapshot.hasError) {
                return Text('Failed to make a request!');
              } else {
                return Text('Loading');
              }
            },
          ),
        ),
      ),
    );
  }
}

尝试更改图像的URL并查看结果:

demo