【问题标题】:Is there a way to avoid getting an exception from a REST request in flutter?有没有办法避免在颤动中从 REST 请求中获取异常?
【发布时间】:2020-05-02 18:00:35
【问题描述】:

我在 Flutter 上开发了一个带有底部导航栏的小应用程序,如果您按下导航栏的某个项目,它将带您进入一个屏幕,一旦打开,它就会执行 http GET 以检索从外部 API 引用。问题是,单击导航栏上的项目后,会出现一个错误,显示时间很短,可能是由于请求尚未完成,因此无法显示结果。有没有办法避免这种情况?

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

class ClientsPage extends StatefulWidget {
  @override
  _ClientsPageState createState() => _ClientsPageState();
}

class _ClientsPageState extends State<ClientsPage> {
  Map data;

  Future<String> getData() async {
    http.Response response = await http.get("https://api.kanye.rest");
    this.setState(() {
      data = json.decode(response.body);
    });
    return "success";
  }

  @override
  void initState() {
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: const Text('Clients Page',
              style: TextStyle(color: Colors.yellow)),
          centerTitle: true,
          backgroundColor: Colors.black,
        ),
        body: new Container(
            child: new Center(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
              new Text(data["quote"]),
              new RaisedButton(
                  child: new Text("Kanye Quote"), onPressed: getData)
            ]))));
  }
}

【问题讨论】:

  • 嗨@João Dias!请不要将您的代码作为屏幕截图发布,将其粘贴到问题中。如果您选择您的代码并按下{}-按钮,它将以等宽显示。
  • 如果我不够清楚,请告诉我。

标签: http flutter


【解决方案1】:

您收到错误消息,因为您定义的 Map data 在您在 Text 小部件中访问之前没有从 api 获取数据。为此,您需要使用 FutureBuilder,它会等到您的请求完成后再显示数据。您可以了解更多关于FutureBuilder here

class ClientsPage extends StatefulWidget {
  @override
  _ClientsPageState createState() => _ClientsPageState();
}

class _ClientsPageState extends State<ClientsPage> {
  Map data;

  Future<String> getData() async {
    http.Response response = await http.get("https://api.kanye.rest");
    this.setState(() {
      data = json.decode(response.body);
    });
    return "success";
  }

  @override
  void initState() {
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: const Text('Clients Page',
              style: TextStyle(color: Colors.yellow)),
          centerTitle: true,
          backgroundColor: Colors.black,
        ),
        body: new Container(
            child: new Center(
                child: new Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      FutureBuilder(
                        future: getData(),
                          builder:(context,snapshot){
                          if(snapshot.hasData){
                            return Text(data["quote"]);
                          }else{
                            return CircularProgressIndicator();
                          }
                         }),
                      new RaisedButton(
                          child: new Text("Kanye Quote"), onPressed: getData)
                    ]))));
  }
}

【讨论】:

    猜你喜欢
    • 2022-10-25
    • 2023-03-23
    • 2011-02-04
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多