RefreshIndicator在FutureBuilder上不起作用?

时间:2019-07-11 10:40:58

标签: flutter dart

这是我的完整代码

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:weathercheck/Weather.dart';
import 'dart:convert';

这是我连接WeatherData类的地方

Future<WeatherData> fetchWeatherdetail() async {
  final response = 
          await http.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22');
  if (response.statusCode == 200) {   
    // If server returns an OK response, parse the JSON.
    return WeatherData.fromJson(json.decode(response.body));

  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }

}





void main(){
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/' : (context) => MyHome(),
      '/weatherResult' : (context) => WeatherResult1()
    }
  )
  );
}

 Widget myAppBar(String txtTitle){
       return AppBar(
          title: Text(txtTitle),
          backgroundColor: Colors.orange[300],  
        );
 }

class MyHome extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: myAppBar('Find your city weather'),
      body: Column(children:[
        TextField(
          onChanged: (text){

          },
        ),
        RaisedButton(
          child: Text('Search'),

          onPressed: (){
            Navigator.pushNamed(context, '/weatherResult');
          },
        ),
      ],)
      );
  }
}



class _WeatherResult1State extends State<WeatherResult1>{
      final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
          new GlobalKey<RefreshIndicatorState>();

 Future<WeatherData> weatherData;

  @override
  void initState() {
    super.initState();
    weatherData = fetchWeatherdetail();  
  }

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: myAppBar('Find your city weather'),
      body:

从这里想刷新但不起作用

        RefreshIndicator(
        key: _refreshIndicatorKey,
        onRefresh: _refresh,
        child:
          FutureBuilder<WeatherData>(
          future: fetchWeatherdetail(),
          builder: (context, snapshot) {
              if (snapshot.hasData) {
                for(var i = 0; i< snapshot.data.weather.length ; i++){
                return Container(    

                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    image: DecorationImage(
                       image: AssetImage('assets/images/london.jpg'),
                       fit: BoxFit.fill
                         )
                  ),                           
                  child:Row(                 
                  children:<Widget>[
                  Column(
                    children: <Widget>[
                  Text('City ID: ', style: TextStyle(fontSize: 20,),),
                  Text('City Name: ', style: TextStyle(fontSize: 20),),
                  Text('Weather condition: ', style: TextStyle(fontSize: 20),),
                  Text('Weather description: ', style: TextStyle(fontSize: 20),)
                  ],),
                  Column(children: <Widget>[
                  Text(snapshot.data.id.toString(), style: TextStyle(fontSize: 20),),
                  Text(snapshot.data.name, style: TextStyle(fontSize: 20),),
                  Text(snapshot.data.weather[i].main, style: TextStyle(fontSize: 20),),
                  Text(snapshot.data.weather[i].description, style: TextStyle(fontSize: 20),  )
                  ],),
                ]));
                 }
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default, show a loading spinner.
              return Center(
                child: CircularProgressIndicator()
              );
          },
        )
      )
      );
  }

这是我的_refresh函数

    Future<Null> _refresh() async{ 
        await Future.delayed(Duration(seconds: 2));
      setState(() {
        weatherData = fetchWeatherdetail();
      }
      );
      return null;
    }
}

我不知道是什么使该代码无法正常工作,refreshIndicator是否不适用于Future builder?或其他东西..我真的卡在这里..以及为什么这个stackoverflow这么难使线程啊..

1 个答案:

答案 0 :(得分:0)

您似乎应该使用ListView来显示列表中的所有项。替换以下代码

for(var i = 0; i< snapshot.data.weather.length ; i++){
    return Container(    
        decoration: BoxDecoration(
           ...

使用

return ListView.builder(
    physics: AlwaysScrollableScrollPhysics(),
    itemBuilder: (context, i){
        WeatherData weatherItem = snapshot.data.weather[i];
        return Container(    
            decoration: BoxDecoration(
                ...
    },
    itemCount: snapshot.data.weather.length,
);