用Flutter单击按钮后的网络请求

Chr*_*her 4 dart flutter

我要在第一个Flutter应用中单击一个按钮后,对OpenWeatherMap-API进行网络请求(Rest API)。基本上,我正在按照本教程进行操作:从Internet上获取数据

因此,我创建了API调用,该调用紧随本教程之后,并且像一个咒语一样工作:

class OpenWeatherApi {
    static const _API_KEY = "asdbaklsadfkasdlfkasdjfl";

    Future<CurrentWeather> getCurrentWeather(String location) async {
        final url =
    "https://api.openweathermap.org/data/2.5/weather?q=$location&APPID=$_API_KEY";
        final response = await get(url);
        final responseJson = json.decode(response.body);
         return new CurrentWeather.fromJson(responseJson);
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在有状态窗口小部件中调用API:

class _MyHomePageState extends State<MyHomePage> {
  String _currentWeather = "";

  void _callWeatherApi() {
    var api = new OpenWeatherApi();
    api.getCurrentWeather("Waldershof, Germany").then((weather) {
      setState(() {
        _currentWeather = weather.getTextualRepresentation();
      });
    }, onError: (error) {
      setState(() {
        _currentWeather = error.toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new TextField(
            decoration: new InputDecoration(
                border: InputBorder.none, hintText: 'Please enter a Location'),
          ),
          new RaisedButton(
            onPressed: () {
              _callWeatherApi();
            },
            child: new Text("Get Weather"),
          ),
          new Text(
            '$_currentWeather',
            style: Theme.of(context).textTheme.display1,
          ),
        ],
      ),
    );
  }
} 
Run Code Online (Sandbox Code Playgroud)

单击RaisedButton,我调用函数_callWeatherApi。此功能执行网络请求并随后更新我的窗口小部件。基本上,它运作良好。

但是在示例中,他们使用FutureBuilder-Widget进行网络请求,这在状态处理方面具有一些不错的优点(例如,显示进度指示器):

new FutureBuilder<Post>(
  future: fetchPost(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return new Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return new Text("${snapshot.error}");
    }

    // By default, show a loading spinner
    return new CircularProgressIndicator();
  },
);
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不知道此FutureBuilder小部件是否可以用于由按钮按下触发的网络请求。

因此,我不知道我对基于按钮按下的网络请求的实现是否是最新的,或者是否可以通过FutureBuilder在Flutter中使用例如或其他窗口小部件来进行改进?

您对我的代码有什么建议吗?

dhu*_*981 6

您无需编写FutureBuilder。没有它,您也可以实现。

这是另一种方法。

编写一个函数以返回_MyHomePageState类中的Progressbar或Text。

Widget getProperWidget(){
    if(apiCall)
      return new CircularProgressIndicator();
    else
      return new Text(
        '$_currentWeather',
        style: Theme.of(context).textTheme.display1,
      );
  }
Run Code Online (Sandbox Code Playgroud)

创建一个本地变量来管理API调用的状态。

String _currentWeather = "";
bool apiCall = false; // New variable
Run Code Online (Sandbox Code Playgroud)

使用该函数替换build方法中的Text小部件,并设置状态apiCall = true。

....
new RaisedButton(
                onPressed: () {
                  setState((){
                    apiCall=true; // Set state like this
                  });
                  _callWeatherApi();
                },
                child: new Text("Get Weather"),
              ),
     getProperWidget()
Run Code Online (Sandbox Code Playgroud)

收到请求的响应后,隐藏进度条,并按以下方式更新_cal​​lWeatherApi函数:

void _callWeatherApi() {
    var api = new OpenWeatherApi();
    api.getCurrentWeather("Waldershof, Germany").then((weather) {
      setState(() {
        apiCall= false; //Disable Progressbar
        _currentWeather = weather.toString();
      });
    }, onError: (error) {
      setState(() {
        apiCall=false; //Disable Progressbar
        _currentWeather = error.toString();
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)