以下 ArgumentError 被抛出构建 WeatherApp(dirty, state: _WeatherAppState#188d9): Invalid argument(s)

时间:2021-07-01 07:41:34

标签: flutter dart

您好,我正在使用 https://www.metaweather.com 创建天气应用程序来获取数据,它在加载数据之前工作正常这里谁可以帮助解决这个应用程序的问题是我在加载数据后加载数据之前收到错误已消失?

 import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    import 'dart:io';
    import 'package:geolocator/geolocator.dart';
    import 'package:intl/intl.dart';
    
    void main() => runApp(WeatherApp());
    
    class WeatherApp extends StatefulWidget {
      @override
      _WeatherAppState createState() => _WeatherAppState();
    }
    
    class _WeatherAppState extends State<WeatherApp> {
      int temperature;
      var minTemperatureForecast = new List(7);
      var maxTemperatureForecast = new List(7);
      String location = 'San Francisco';
      int woeid = 2487956;
      String weather = 'clear';
      String abbreviation = '';
      var abbreviationForecast = new List(7);
      String errorMessage = '';
    
      final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
    
      Position _currentPosition;
      String _currentAddress;
    
      String searchApiUrl =
          'https://www.metaweather.com/api/location/search/?query=';
      String locationApiUrl = 'https://www.metaweather.com/api/location/';
    
      initState() {
        super.initState();
        fetchLocation();
        fetchLocationDay();
      }
    
      void fetchSearch(String input) async {
        try {
          var searchResult = await http.get(searchApiUrl + input);
          var result = json.decode(searchResult.body)[0];
    
          setState(() {
            location = result["title"];
            woeid = result["woeid"];
            errorMessage = '';
          });
        } catch (error) {
          setState(() {
            errorMessage =
            "Sorry, we don't have data about this city. Try another one.";
          });
        }
      }
    
      void fetchLocation() async {
        var locationResult = await http.get(locationApiUrl + woeid.toString());
        var result = json.decode(locationResult.body);
        var consolidated_weather = result["consolidated_weather"];
        var data = consolidated_weather[0];
    
        setState(() {
          temperature = data["the_temp"].round();
          weather = data["weather_state_name"].replaceAll(' ', '').toLowerCase();
          abbreviation = data["weather_state_abbr"];
        });
      }
    
      void fetchLocationDay() async {
        var today = new DateTime.now();
        for (var i = 0; i < 7; i++) {
          var locationDayResult = await http.get(locationApiUrl +
              woeid.toString() +
              '/' +
              new DateFormat('y/M/d')
                  .format(today.add(new Duration(days: i + 1)))
                  .toString());
          var result = json.decode(locationDayResult.body);
          var data = result[0];
    
          setState(() {
            minTemperatureForecast[i] = data["min_temp"].round();
            maxTemperatureForecast[i] = data["max_temp"].round();
            abbreviationForecast[i] = data["weather_state_abbr"];
          });
        }
      }
    
      void onTextFieldSubmitted(String input) async {
        await fetchSearch(input);
        await fetchLocation();
        await fetchLocationDay();
      }
    
      _getCurrentLocation() {
        geolocator
            .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
            .then((Position position) {
          setState(() {
            _currentPosition = position;
          });
    
          _getAddressFromLatLng();
        }).catchError((e) {
          print(e);
        });
      }
    
      _getAddressFromLatLng() async {
        try {
          List<Placemark> p = await geolocator.placemarkFromCoordinates(
              _currentPosition.latitude, _currentPosition.longitude);
    
          Placemark place = p[0];
    
          setState(() {
            _currentAddress =
            "${place.locality}, ${place.postalCode}, ${place.country}";
          });
          onTextFieldSubmitted(place.locality);
          print(place.locality);
        } catch (e) {
          print(e);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('images/$weather.png'),
                  fit: BoxFit.cover,
                  colorFilter: new ColorFilter.mode(
                      Colors.black.withOpacity(0.6), BlendMode.dstATop),
                ),
              ),
              child: temperature == null
                  ? Center(child: CircularProgressIndicator())
                  : Scaffold(
                appBar: AppBar(
                  actions: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(right: 20.0),
                      child: GestureDetector(
                        onTap: () {
                          _getCurrentLocation();
                        },
                        child: Icon(Icons.location_city, size: 36.0),
                      ),
                    )
                  ],
                  backgroundColor: Colors.transparent,
                  elevation: 0.0,
                ),
                resizeToAvoidBottomInset: false,
                backgroundColor: Colors.transparent,
                body: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Column(
                      children: <Widget>[
                        Center(
                          child: Image.network(
                            'https://www.metaweather.com/static/img/weather/png/' +
                                abbreviation +
                                '.png',
                            width: 100,
                          ),
                        ),
                        Center(
                          child: Text(
                            temperature.toString() + ' °C',
                            style: TextStyle(
                                color: Colors.white, fontSize: 60.0),
                          ),
                        ),
                        Center(
                          child: Text(
                            location,
                            style: TextStyle(
                                color: Colors.white, fontSize: 40.0),
                          ),
                        ),
                      ],
                    ),
                    SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: <Widget>[
                          for (var i = 0; i < 7; i++)
                            forecastElement(
                                i + 1,
                                abbreviationForecast[i],
                                minTemperatureForecast[i],
                                maxTemperatureForecast[i]),
                        ],
                      ),
                    ),
                    Column(
                      children: <Widget>[
                        Container(
                          width: 300,
                          child: TextField(
                            onSubmitted: (String input) {
                              onTextFieldSubmitted(input);
                            },
                            style:
                            TextStyle(color: Colors.white, fontSize: 25),
                            decoration: InputDecoration(
                              hintText: 'Search another location...',
                              hintStyle: TextStyle(
                                  color: Colors.white, fontSize: 18.0),
                              prefixIcon:
                              Icon(Icons.search, color: Colors.white),
                            ),
                          ),
                        ),
                        Padding(
                          padding:
                          const EdgeInsets.only(right: 32.0, left: 32.0),
                          child: Text(errorMessage,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.redAccent,
                                  fontSize:
                                  Platform.isAndroid ? 15.0 : 20.0)),
                        )
                      ],
                    ),
                  ],
                ),
              )),
        );
      }
    }
    
    Widget forecastElement(
        daysFromNow, abbreviation, minTemperature, maxTemperature) {
      var now = new DateTime.now();
      var oneDayFromNow = now.add(new Duration(days: daysFromNow));
      return Padding(
        padding: const EdgeInsets.only(left: 16.0),
        child: Container(
          decoration: BoxDecoration(
            color: Color.fromRGBO(205, 212, 228, 0.2),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: <Widget>[
                Text(
                  new DateFormat.E().format(oneDayFromNow),
                  style: TextStyle(color: Colors.white, fontSize: 25),
                ),
                Text(
                  new DateFormat.MMMd().format(oneDayFromNow),
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 16.0, bottom: 16.0),
                  child: Image.network(
                    'https://www.metaweather.com/static/img/weather/png/' +
                        abbreviation +
                        '.png',
                    width: 50,
                  ),
                ),
                Text(
                  'High: ' + maxTemperature.toString() + ' °C',
                  style: TextStyle(color: Colors.white, fontSize: 20.0),
                ),
                Text(
                  'Low: ' + minTemperature.toString() + ' °C',
                  style: TextStyle(color: Colors.white, fontSize: 20.0),
                ),
              ],
            ),
          ),
        ),
      );
    }


======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building WeatherApp(dirty, state: _WeatherAppState#188d9):
Invalid argument(s)

The relevant error-causing widget was: 
  WeatherApp file:///Users/apple/Downloads/flutter-weather-app-starterkit-master/weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1      forecastElement (package:weatherapp/main.dart:270:71)
#2      _WeatherAppState.build (package:weatherapp/main.dart:198:25)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building WeatherApp(dirty, state: _WeatherAppState#188d9):
Invalid argument(s)

The relevant error-causing widget was: 
  WeatherApp file:///Users/apple/Downloads/flutter-weather-app-starterkit-master/weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1      forecastElement (package:weatherapp/main.dart:270:71)
#2      _WeatherAppState.build (package:weatherapp/main.dart:198:25)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building WeatherApp(dirty, state: _WeatherAppState#188d9):
Invalid argument(s)

The relevant error-causing widget was: 
  WeatherApp file:///Users/apple/Downloads/flutter-weather-app-starterkit-master/weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1      forecastElement (package:weatherapp/main.dart:270:71)
#2      _WeatherAppState.build (package:weatherapp/main.dart:198:25)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building WeatherApp(dirty, state: _WeatherAppState#188d9):
Invalid argument(s)

The relevant error-causing widget was: 
  WeatherApp file:///Users/apple/Downloads/flutter-weather-app-starterkit-master/weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1      forecastElement (package:weatherapp/main.dart:270:71)
#2      _WeatherAppState.build (package:weatherapp/main.dart:198:25)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following ArgumentError was thrown building WeatherApp(dirty, state: _WeatherAppState#188d9):
Invalid argument(s)

The relevant error-causing widget was: 
  WeatherApp file:///Users/apple/Downloads/flutter-weather-app-starterkit-master/weather_app/lib/main.dart:8:23
When the exception was thrown, this was the stack: 
#0      _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1      forecastElement (package:weatherapp/main.dart:270:71)
#2      _WeatherAppState.build (package:weatherapp/main.dart:198:25)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4691:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4574:15)
...
====================================================================================================
W/libEGL  (13385): EGLNativeWindowType 0x7f55747010 disconnect failed
W/libEGL  (13385): EGLNativeWindowType 0x7f55746010 disconnect failed
D/mali_winsys(13385): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
D/mali_winsys(13385): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
E/BpSurfaceComposerClient(13385): Failed to transact (-1)
E/BpSurfaceComposerClient(13385): Failed to transact (-1)
W/InputMethodManager(13385): startInputReason = 1
I/hwaps   (13385): JNI_OnLoad
I/zygote64(13385): Do partial code cache collection, code=61KB, data=45KB
I/zygote64(13385): After code cache collection, code=61KB, data=46KB
I/zygote64(13385): Increasing code cache capacity to 256KB
V/InputMethodManager(13385): Reporting focus gain, without startInput
W/libEGL  (13385): EGLNativeWindowType 0x7f4c078010 disconnect failed
W/libEGL  (13385): EGLNativeWindowType 0x7f55746010 disconnect failed
D/mali_winsys(13385): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
D/mali_winsys(13385): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
W/InputMethodManager(13385): startInputReason = 1
D/KeyEvent(13385): obtain, mHwFlags=0
D/KeyEvent(13385): obtain, mHwFlags=0
W/libEGL  (13385): EGLNativeWindowType 0x7f78bc5010 disconnect failed
W/libEGL  (13385): EGLNativeWindowType 0x7f55746010 disconnect failed
W/InputMethodManager(13385): startInputReason = 3
W/InputMethodManager(13385): reStartinput failed, need refresh!
E/libEGL  (13385): call to OpenGL ES API with no current context (logged once per thread)
D/ActivityThread(13385): Remove activity client record, r= ActivityRecord{5eb917c token=android.os.BinderProxy@72a3e23 {com.example.weatherapp/com.example.weatherapp.MainActivity}} token= android.os.BinderProxy@72a3e23

0 个答案:

没有答案