首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行天气应用程序时会出现此错误,我使用json和http库来获取数据,但我不知道为什么会出现此错误

运行天气应用程序时会出现此错误,我使用json和http库来获取数据,但我不知道为什么会出现此错误
EN

Stack Overflow用户
提问于 2020-09-30 02:19:34
回答 1查看 199关注 0票数 0

错误代码E/flutter (25456):错误:flutter/lib/ui/ui_dart_state.cc(157)未处理异常: NoSuchMethodError:方法'[]‘被调用为null。E/颤振(25456):接收器:空E/颤振(25456):尝试调用:E/颤振(25456):#0 Object.noSuchMethod (飞镖:核心补丁/对象_patch.dart:53:5)E/颤振(25456):#1

_WeatherState.fetchLocationUpDate。(package:tast_project/screenes/screenweather.dart:31:27) E/颤振(25456):#2 State.setState (package:flutter/src/widgets/framework.dart:1148:30) E/颤振(25456):#3 _WeatherState.fetchLocationUpDate (package:tast_project/screenes/screenweather.dart:30:5) E/颤振(25456):E/颤振(25456):#4

(package:tast_project/screenes/screenweather.dart:42:5) E/颤振(25456):#5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58) E/颤振(25456):#6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/颤振(25456):#7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#8 (package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#9 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/颤振(25456):#10 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#11 Element.updateChild (包: flutter /src/widget/framework)。飞镖:2988:12)E/颤振(25456):#12 (package:flutter/src/widgets/framework.dart:4243:16) E/颤振(25456):#13 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/颤振(25456):#14 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/颤振(25456):#15 ComponentElement.mount (包装)4201:4201:5)E/颤振(25456):#16 (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#17 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#18 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/颤振(25456):##19 (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#20 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#21 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/颤振(25456):#22 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E(package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#24 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16) E/颤振(25456):#25 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/颤振(25456):#26 ComponentElement._firstBuild (软件包:颤振/src/小部件/E/颤振(25456):#27 (package:flutter/src/widgets/framework.dart:4381:11) E/颤振(25456):#28 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/颤振(25456):#29 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#30 Element.updateChild(package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#31 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/颤振(25456):#32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#33 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#34 (package:flutter/src/widgets/framework.dart:5445:14) E/颤振(25456):#35 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/颤振(25456):#36 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/颤振(25456):#37 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)E/颤振(25456):#38 (package:flutter/src/widgets/framework.dart:3947:5) E/颤振(25456):#39 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/颤振(25456):#40 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11) E/颤振(25456):#41 ComponentElement.mount (包装:ComponentElement._firstBuild/src)/widgets/Frawork.DART:4201:5)E/ (package:flutter/src/widgets/framework.dart:2988:12) (25456):#42 Element.inflateWidget Element.inflateWidget E/flutter (25456):#43 Element.updateChild Element.updateChild E/flutter (25456):#44 ComponentElement.performRebuild (包:Element.inflateWidget/src/widgets/Frawork.da)

代码语言:javascript
复制
   Flutter code weather

  

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class Weather extends StatefulWidget {
      @override
      _WeatherState createState() => _WeatherState();
    }
    const ipkay = '14f4090b86e2548527113ccac56a5ae4';
    class _WeatherState extends State<Weather> {
      var temp = 0;
      String city='';
      //var id = 4099194;
      String location ;
      var textEditingController = TextEditingController();
      fetchSearch(String input) async {
          http.Response response = await http.get(
             "http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=" + input);
          var result = json.decode(response.body);
           setState(() {
             location =result['name'];
           });}
    
      fetchLocationUpDate()async{
        http.Response response = await http.get(
         'http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=$location');
        var result = json.decode(response.body);
        setState(() {
          temp =result['main']['temp'];
           city =result['name'];
        });}
    
      glo(String city){
        fetchSearch(city);
        fetchLocationUpDate();}
    
      @override
      void initState() {
        super.initState();
        fetchLocationUpDate();}
    
      @override
      Widget build(BuildContext context) {
        Size size = MediaQuery.of(context).size;
        return Scaffold(
          backgroundColor: Colors.transparent,
          body: SafeArea(
            child: Container(
              width: size.width,
              height: size.height,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                        'assetes/img/night.jpg',
                      ),
                      fit: BoxFit.fill)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '${temp.toString()} C°',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                  Text(
                    '$city',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                  Card(
                    child: TextField(
                      onSubmitted: (String city) {
                        glo(city);
                      },
                      controller: textEditingController,
                      decoration: InputDecoration(
                        hintText: 'please entre city',
                        prefixIcon: Icon(Icons.search),
                      ),
                    ),
                  ),
                )
                ],
              ),
            ),
          ),
        );
      }
EN

回答 1

Stack Overflow用户

发布于 2020-09-30 03:14:34

您可以复制粘贴,运行下面的完整代码

步骤1:double temp = 0;

步骤2:glo需要asyncawait

代码语言:javascript
复制
glo(String city) async {
    await fetchSearch(city);
    await fetchLocationUpDate();
  }

第三步:检查是否存在城市

代码语言:javascript
复制
if (result["cod"] == 200) {
      setState(() {
        location = result['name'];
        print("locaton $location");
      });
    }

工作演示

全码

代码语言:javascript
复制
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Weather extends StatefulWidget {
  @override
  _WeatherState createState() => _WeatherState();
}

const ipkay = '14f4090b86e2548527113ccac56a5ae4';

class _WeatherState extends State<Weather> {
  double temp = 0;
  //var id = 4099194;
  String location;
  var textEditingController = TextEditingController();
  fetchSearch(String input) async {
    http.Response response = await http.get(
        "http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=" +
            input);
    var result = json.decode(response.body);
    print("fetchSearch ${response.body}");
    if (result["cod"] == 200) {
      setState(() {
        location = result['name'];
        print("locaton $location");
      });
    }
  }

  fetchLocationUpDate() async {
    print("location to string ${location.toString()}");
    http.Response response = await http.get(
        'http://api.openweathermap.org/data/2.5/weather?units=metric&appid=14f4090b86e2548527113ccac56a5ae4&q=' +
            location.toString());
    print("LocationUpdate ${response.body}");
    var result = json.decode(response.body);
    if (result["cod"] == 200) {
      setState(() {
        temp = result['main']['temp'];
      });
    }
  }

  glo(String city) async {
    await fetchSearch(city);
    await fetchLocationUpDate();
  }

  @override
  void initState() {
    super.initState();
    //fetchLocationUpDate();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SafeArea(
        child: Container(
          width: size.width,
          height: size.height,
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(
                    'https://picsum.photos/250?image=9',
                  ),
                  fit: BoxFit.fill)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '${temp.toDouble()} C°',
                style: TextStyle(color: Colors.white, fontSize: 30),
              ),
              Card(
                child: TextField(
                  onSubmitted: (String city) {
                    glo(city);
                  },
                  controller: textEditingController,
                  decoration: InputDecoration(
                    hintText: 'please entre city',
                    prefixIcon: Icon(Icons.search),
                  ),
                ),
              ),
              //              RaisedButton(
              //                onPressed: () {
              //                  glo();
              //                },
              //              )
            ],
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Weather(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64129986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档