当前位置: 首页 > 知识库问答 >
问题:

运行天气应用程序时出现此错误我使用json和超文本传输协议库获取数据,但我不知道为什么会出现此错误

舒浩邈
2023-03-14

错误代码

E/flatter(25456):[ERROR:flatter/lib/ui/ui\u dart\u state.cc(157)]未处理的异常:NoSuchMethodError:对null调用了方法“[]”。E/flatter(25456):接收器:空E/flatter(25456):尝试调用:E/flatter(25456):#0对象。无此方法(省道:核心补丁/对象补丁。省道:53:5)E/颤振(25456):#1
\u天气状态。fetchLocationUpDate。(套餐:tast_项目/screens/screenweather.dart:31:27)E/flift(25456):#2状态。setState(包:flatter/src/widgets/framework.dart:1148:30)E/flatter(25456):#3_WeatherState。fetchLocationUpDate(包:tast_项目/screens/screenweather.dart:30:5)E/flatter(25456):E/flatter(25456):#4
\u WeatherState。initState(包:tast_项目/screens/screenweather.dart:42:5)E/flift(25456):#5 StatefulElement_firstBuild(包:flatter/src/widgets/framework.dart:4355:58)E/flatter(25456):#6个组件元素。挂载(包:flatter/src/widgets/framework.dart:4201:5)E/flatter(25456):#7元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#8元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#9 SingleChildRenderObjectElement。挂载(包:flatter/src/widgets/framework.dart:5445:14)E/flatter(25456):#10元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#11元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#12组件元素。performRebuild(包:flatter/src/widgets/framework.dart:4243:16)E/flatter(25456):#13元素。重建(包:flatter/src/widgets/framework.dart:3947:5)E/flatter(25456):#14组件元素_firstBuild(包:flatter/src/widgets/framework.dart:4206:5)E/flatter(25456):#15个组件元素。挂载(包:flatter/src/widgets/framework.dart:4201:5)E/flatter(25456):#16元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#17元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#18 SingleChildRenderObjectElement。挂载(包:flatter/src/widgets/framework.dart:5445:14)E/flatter(25456):#19元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#20元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#21 SingleChildRenderObjectElement。挂载(包:flatter/src/widgets/framework.dart:5445:14)E/flatter(25456):#22元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#23元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#24组件元素。performRebuild(包:flatter/src/widgets/framework.dart:4243:16)E/flatter(25456):#25元素。重建(包:flatter/src/widgets/framework.dart:3947:5)E/flatter(25456):#26组件元素_firstBuild(包:flatter/src/widgets/framework.dart:4206:5)E/flatter(25456):#27 StatefulElement_firstBuild(包:flatter/src/widgets/framework.dart:4381:11)E/flatter(25456):#28组件元素。挂载(包:flatter/src/widgets/framework.dart:4201:5)E/flatter(25456):#29元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#30元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#31 SingleChildRenderObjectElement。挂载(包:flatter/src/widgets/framework.dart:5445:14)E/flatter(25456):#32元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#33元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#34 SingleChildRenderObjectElement。挂载(包:flatter/src/widgets/framework.dart:5445:14)E/flatter(25456):#35元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#36元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#37组件元素。performRebuild(包:flatter/src/widgets/framework.dart:4243:16)E/flatter(25456):#38元素。重建(包:flatter/src/widgets/framework.dart:3947:5)E/flatter(25456):#39组件元素_firstBuild(包:flatter/src/widgets/framework.dart:4206:5)E/flatter(25456):#40 StatefulElement_firstBuild(包:flatter/src/widgets/framework.dart:4381:11)E/flatter(25456):#41组件元素。挂载(包:flatter/src/widgets/framework.dart:4201:5)E/flatter(25456):#42元素。充气小部件(包:flatter/src/widgets/framework.dart:3194:14)E/flatter(25456):#43元素。updateChild(包:flatter/src/widgets/framework.dart:2988:12)E/flatter(25456):#44组件元素。PerformBuild(包:flatter/src/widgets/framework.da


   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),
                      ),
                    ),
                  ),
                )
                ],
              ),
            ),
          ),
        );
      }

  

共有1个答案

文建业
2023-03-14

您可以复制粘贴运行下面的完整代码
步骤1:双temp=0;
步骤2:glo需要异步等待

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

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

if (result["cod"] == 200) {
      setState(() {
        location = result['name'];
        print("locaton $location");
      });
    }

工作演示

完整代码

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),
      ),
    );
  }
}
 类似资料:
  • 问题内容: 我正在尝试使用DB2运行一个简单的SQL语句,并且遇到了一些问题。我想在txt / db2文件中有一个脚本,并让引擎处理所有命令 这是脚本: 当我运行db2 -f / pathtofile时,我得到: 我究竟做错了什么?我的脚本有问题吗?另外,为什么没有“;”也能正常工作 我的陈述结尾处的终止符? 谢谢, 问题答案: 可能会有帮助, http://www.uc.edu/R/r25/do

  • 在Android mobile上运行应用程序时出现此错误 正在调试模式下在DRA LX2上启动lib\main.dart...正在运行分级任务“Assemble Debug”...√build build\app\outputs\flutter-apk\app-debug.apk。正在安装build\app\outputs\flutter-apk\app.apk...错误:ADB退出,退出代码为1

  • 问题内容: 我正在执行以下AJAX调用: 而且没有收到预期的警报消息。相反,Firebug说我收到“未实现501”。 为什么?我需要怎么做才能解决此问题? 如果我转到Firebug中与AJAX调用相对应的URL,则会下载一个JSON文件,其中包含预期的数据。 我注意到的一件事是,萤火虫说的是OPTIONS而不是GET: 替代文字http://grab.by/grabs/b1a13d92a4fc69

  • 问题内容: 在CentOS 5 linux上使用一些基本的Java应用程序,我已设置为指向其中包含和 我有文件 和 当我运行,并在一切完美 但是,当我运行从内上我得到一个文件未找到错误,特别是 为什么会这样呢? 感谢所有帮助 问题答案: 您不应将 类路径 设置为指向您的JDK bin目录-而是应该是 PATH 环境变量,它与类路径的作用不同。(classpath定义了包含已编译的Java .cla

  • 文件"C:\Program Data\Anaconda3\Script\tensorboard-script.py",第10行,sys.exit(run_main())文件"C:\Program Data\Anaconda3\lib\site-包\拉伸板\main.py",第57行,run_mainapp.run(tensorboard.main,flags_parser=tensorboard.