Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Api 在构造函数中调用setState():_WeatherState#823a5(生命周期状态:已创建,无小部件,未安装)错误抖动_Api_Flutter_Dart - Fatal编程技术网

Api 在构造函数中调用setState():_WeatherState#823a5(生命周期状态:已创建,无小部件,未安装)错误抖动

Api 在构造函数中调用setState():_WeatherState#823a5(生命周期状态:已创建,无小部件,未安装)错误抖动,api,flutter,dart,Api,Flutter,Dart,天气空气污染指数网页 请帮助我,我的代码有问题,我想从mycity变量更改myURL变量,我有一套city方法: 编辑器错误:在构造函数中调用了setState():#WeatherState 823a5(生命周期状态:已创建,无小部件,未装入) 导入'dart:convert'; 进口“包装:颤振/材料.省道”; 导入“package:marwa_app/component/myResponsiveLibrary.dart”; 导入“包装:marwa_app/component/Logo.da

天气空气污染指数网页

请帮助我,我的代码有问题,我想从mycity变量更改myURL变量,我有一套city方法:

编辑器错误:在构造函数中调用了setState():#WeatherState 823a5(生命周期状态:已创建,无小部件,未装入)

导入'dart:convert';
进口“包装:颤振/材料.省道”;
导入“package:marwa_app/component/myResponsiveLibrary.dart”;
导入“包装:marwa_app/component/Logo.dart”;
导入“package:marwa_app/component/MyDrawer.dart”;
将“package:http/http.dart”导入为http;
类Weather扩展StatefulWidget{
@凌驾
_WeatherState createState();
}
类WeatherState扩展状态{
列出我的城市=[‘亚喀巴’、‘安曼’];
int i=0;
无效城市值(值){
设置状态(){
i=值;
});
}
@凌驾
Future getData()异步{
字符串myURL=wait'http://api.openweathermap.org/data/2.5/forecast?q=${mycity[i]}&appid=41a6cd80a840ce00a3c77b8ba1a04022&units=metric';
http.Response-Response=wait-http.get(myURL);
返回json.decode(response.body);
}
小部件构建(构建上下文){
返回脚手架(
背景颜色:MainModel().mainColor,
appBar:appBar(
背景颜色:颜色(0xff323266),
领先:IconButton(
图标:图标(
Icons.u处于活动状态,
颜色:MainModel().thirdColor,
),
onPressed:()=>{}),
标题:Logo(),
标题:对,
行动:[
建筑商(
生成器:(上下文)=>IconButton(
图标:图标(
图标菜单,
颜色:MainModel().thirdColor,
),
onPressed:()=>Scaffold.of(context.openEndDrawer(),
工具提示:MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
收尾抽屉(
child:MyDrawer(),
),
正文:widgetMyData()
);
}
}
Widget widgetMyData(){
返回FutureBuilder(future:_WeatherState().getData(),
生成器:(构建上下文上下文,异步快照snapshop){
最终宽度屏幕=MediaQuery.of(context).size.width;
if(snapshop.hasData){
地图内容=snapshop.data;
返回容器(
颜色:MainModel().secondColor,
儿童:中心(
子:ListView(
物理学:NeverscrollableScroll物理学(),
儿童:[
填充(填充:仅限边集(顶部:20)),
容器(
边距:EdgeInsets.symmetric(水平:MainModel().setPadding(MainModel().largePadding,widthScreen)),
身高:300,
装饰:盒子装饰(
boxShadow:[
箱形阴影(
颜色:颜色。黑色。不透明度(0.15),
扩展半径:5,
半径:5,
偏移量:偏移量(2,2),//更改阴影的位置
),],
borderRadius:borderRadius.all(半径圆形(40)),
梯度:线性梯度(
开始:Alignment.topLeft,
结束:对齐。右下角,
颜色:[
MainModel().mainColor,MainModel().secondColor
])
),
子:列(
儿童:[
填充(填充:EdgeInsets.only(顶部:MainModel().setPadding(MainModel().smallPadding,widthScreen)),),
Image.network('http://openweathermap.org/img/w/${content[“list”][0][“weather”][0][“icon”]}.png',
颜色:MainModel().whiteColor.withOpacity(0.7),
适合:BoxFit.contain,
宽度:120,),
文本(“${content['list'][0]['weather'][0]['description']}”,样式:TextStyle(
fontSize:MainModel().setFont(MainModel().middleFont,widthScreen),
颜色:MainModel().whiteColor.withOpacity(0.7),
),),
Padding(Padding:EdgeInsets.only(顶部:MainModel().setPadding(MainModel().largePadding*1.5,宽度屏幕)),
文本(${content['list'][0]['main']['temp']}\u00b0C),
样式:TextStyle(
fontSize:MainModel().setFont(MainModel().largeFont*1.5,宽屏幕),
颜色:MainModel().whiteColor,
fontWeight:fontWeight.bold
),),
容器(
对齐:对齐.center,
子项:文本(${content['city']['name']}),样式:TextStyle(
fontSize:MainModel().setFont(MainModel().middleFont,widthScreen),
颜色:MainModel().whiteColor,
),)
),
Padding(Padding:EdgeInsets.only(顶部:MainModel().setPadding(MainModel().largePadding*1.5,宽度屏幕)),
划船(
mainAxisAlignment:mainAxisAlignment.spaceAround,
儿童:[
文本(${content['list'][0]['main']['temp_max']}\u00b0C),样式:TextStyle(
fontSize:MainModel().setFont(MainModel().middleFont,widthScreen),
颜色:MainModel().whiteColor,
fontWeight:fontWeight.bold
),),
文本(${content['list'][0]['main']['
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:marwa_app/component/myResponsiveLibrary.dart';
import 'package:marwa_app/component/Logo.dart';
import 'package:marwa_app/component/MyDrawer.dart';
import 'package:http/http.dart' as http;


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

}


class _WeatherState extends State<Weather> {
  List <String> mycity = ['aqaba','amman'];
  int i= 0;

  void cityValue(value) {
    setState(() {
      i = value;
    });
  }
  @override

  Future<Map> getData() async{
      String myURL = await 'http://api.openweathermap.org/data/2.5/forecast?q=${mycity[i]}&appid=41a6cd80a840ce00a3c77b8ba1a04022&units=metric';
      http.Response response = await http.get(myURL);
      return json.decode(response.body);
  }


  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: MainModel().mainColor,
        appBar: AppBar(
          backgroundColor: Color(0xff323266),
          leading: IconButton(
              icon: Icon(
                Icons.notifications_active,
                color: MainModel().thirdColor,
              ),
              onPressed: () => {}),
          title: Logo(),
          centerTitle: true,
          actions: [
            Builder(
              builder: (context) => IconButton(
                icon: Icon(
                  Icons.menu,
                  color: MainModel().thirdColor,
                ),
                onPressed: () => Scaffold.of(context).openEndDrawer(),
                tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
              ),
            ),
          ],
        ),
        endDrawer: Drawer(
          child: MyDrawer(),
        ),
        body: widgetMyData()
    );
  }
}
Widget widgetMyData() {

  return FutureBuilder(future: _WeatherState().getData(),
      builder: (BuildContext context, AsyncSnapshot<Map> snapshop){
        final widthScreen = MediaQuery.of(context).size.width;
        if(snapshop.hasData){
          Map content = snapshop.data;


          return Container(
            color: MainModel().secondColor,
            child: Center(
              child: ListView(
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                Padding(padding: EdgeInsets.only(top: 20)),

                Container(
                  margin: EdgeInsets.symmetric(horizontal: MainModel().setPadding(MainModel().largePadding, widthScreen)),
                  height: 300,
                  decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.15),
                          spreadRadius: 5,
                          blurRadius: 5,
                          offset: Offset(2, 2), // changes position of shadow
                        ),],
                      borderRadius: BorderRadius.all(Radius.circular(40)),
                      gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            MainModel().mainColor, MainModel().secondColor
                          ])
                  ),
                  child: Column(
                    children: [
                      Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().smallPadding, widthScreen)),),
                      Image.network('http://openweathermap.org/img/w/${content["list"][0]["weather"][0]["icon"]}.png',
                        color: MainModel().whiteColor.withOpacity(0.7),
                        fit: BoxFit.contain,
                        width: 120,),
                      Text('${content['list'][0]['weather'][0]['description']}',style: TextStyle(
                        fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
                        color: MainModel().whiteColor.withOpacity(0.7),
                      ),),
                      Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 1.5, widthScreen)),),
                      Text("${content['list'][0]['main']['temp']}\u00b0C",
                        style: TextStyle(
                            fontSize: MainModel().setFont(MainModel().largeFont * 1.5, widthScreen),
                            color: MainModel().whiteColor,
                            fontWeight: FontWeight.bold
                        ),),
                      Container(
                          alignment: Alignment.center,
                          child: Text("${content['city']['name']}",style: TextStyle(
                            fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
                            color: MainModel().whiteColor,
                          ),)
                      ),
                      Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 1.5, widthScreen)),),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text("${content['list'][0]['main']['temp_max']}\u00b0C",style: TextStyle(
                              fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
                              color: MainModel().whiteColor,
                              fontWeight: FontWeight.bold
                          ),),
                          Text("${content['list'][0]['main']['temp_min']}\u00b0C",style: TextStyle(
                              fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
                              color: MainModel().whiteColor,
                              fontWeight: FontWeight.bold
                          ),),
                        ],
                      ),
                    ],
                  ),
                ),
                Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 2, widthScreen))),
                SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
                        Container(
                            height: MainModel().setSize(MainModel().largeSize, widthScreen),
                            width: MainModel().setSize(MainModel().largeSize, widthScreen),
                            decoration: BoxDecoration(
                              color: Color(0xffFFB20F),
                              borderRadius: BorderRadius.all(Radius.circular(40.0)),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),

                              ],
                            )
                        ),
                        Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),

                        Container(
                            height: MainModel().setSize(MainModel().largeSize, widthScreen),
                            width: MainModel().setSize(MainModel().largeSize, widthScreen),
                            decoration: BoxDecoration(
                              color: Color(0xff0DA6A6),
                              borderRadius: BorderRadius.all(Radius.circular(40.0)),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
                              ],
                            )
                        ),
                        Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),

                        Container(
                            height: MainModel().setSize(MainModel().largeSize, widthScreen),
                            width: MainModel().setSize(MainModel().largeSize, widthScreen),
                            decoration: BoxDecoration(
                              color: Color(0xff6D5DF1),
                              borderRadius: BorderRadius.all(Radius.circular(40.0)),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
                              ],
                            )
                        ),
                        Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
                        FlatButton(onPressed: () {
                          _WeatherState().cityValue(1);
                        },
                            child: Container(
                                height: MainModel().setSize(MainModel().largeSize, widthScreen),
                                width: MainModel().setSize(MainModel().largeSize, widthScreen),
                                decoration: BoxDecoration(
                                  color: Color(0xffFF0F97),
                                  borderRadius: BorderRadius.all(Radius.circular(40.0)),
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text('click'),
                                    Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
                                  ],
                                )
                            ),
                        ),
                        Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),

                      ],
                    ))
              ]),
            ),
          );
        }else{
          return Container(
            child: Text('sorry you data is not found'),
          );
        }
      }
  );
}
  Future<Map> _future;
  ...
  @override
  initState() {
    _future = getData();
    super.initState();
  }
  ...
  body: widgetMyData(_future, cityValue));
  
  ...
  Widget widgetMyData(Future<Map> _future, Function callback) {
     return FutureBuilder(
       future: _future,
       ...
       FlatButton(
            onPressed: () {
              callback(1);
            },
            child: Text('click'))
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

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

class _WeatherState extends State<Weather> {
  List<String> mycity = ['aqaba', 'amman'];
  int i = 0;
  Future<Map> _future;

  void cityValue(value) {
    setState(() {
      i = value;
      _future = getData();
    });
  }

  @override
  initState() {
    _future = getData();
    super.initState();
  }

  Future<Map> getData() async {
    String myURL =
        await 'https://api.openweathermap.org/data/2.5/forecast?q=${mycity[i]}&appid=41a6cd80a840ce00a3c77b8ba1a04022&units=metric';
    http.Response response = await http.get(myURL);
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //backgroundColor: MainModel().mainColor,
        appBar: AppBar(
          backgroundColor: Color(0xff323266),
          leading: IconButton(
              icon: Icon(
                Icons.notifications_active,
                //color: MainModel().thirdColor,
              ),
              onPressed: () => {}),
          title: Text("Logo()"),
          centerTitle: true,
          actions: [
            Builder(
              builder: (context) => IconButton(
                icon: Icon(
                  Icons.menu,
                  //color: MainModel().thirdColor,
                ),
                onPressed: () => Scaffold.of(context).openEndDrawer(),
                tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
              ),
            ),
          ],
        ),
        body: widgetMyData(_future, cityValue));
  }
}

Widget widgetMyData(Future<Map> _future, Function callback) {
  return FutureBuilder(
      future: _future,
      builder: (BuildContext context, AsyncSnapshot<Map> snapshop) {
        final widthScreen = MediaQuery.of(context).size.width;
        if (snapshop.hasData) {
          Map content = snapshop.data;

          return Container(
            child: Center(
              child:
                  ListView(physics: NeverScrollableScrollPhysics(), children: [
                Padding(padding: EdgeInsets.only(top: 20)),
                Container(
                  height: 300,
                  decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.15),
                          spreadRadius: 5,
                          blurRadius: 5,
                          offset: Offset(2, 2), // changes position of shadow
                        ),
                      ],
                      borderRadius: BorderRadius.all(Radius.circular(40)),
                      gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [Colors.blue, Colors.red])),
                  child: Column(
                    children: [
                      Image.network(
                        'https://openweathermap.org/img/w/${content["list"][0]["weather"][0]["icon"]}.png',
                        //color: MainModel().whiteColor.withOpacity(0.7),
                        fit: BoxFit.contain,
                        width: 120,
                      ),
                      Text(
                        '${content['list'][0]['weather'][0]['description']}',
                      ),
                      Text(
                        "${content['list'][0]['main']['temp']}\u00b0C",
                      ),
                      Container(
                          alignment: Alignment.center,
                          child: Text(
                            "${content['city']['name']}",
                          )),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text(
                            "${content['list'][0]['main']['temp_max']}\u00b0C",
                          ),
                          Text(
                            "${content['list'][0]['main']['temp_min']}\u00b0C",
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        FlatButton(
                            onPressed: () {
                              callback(1);
                            },
                            child: Text('click')),
                      ],
                    ))
              ]),
            ),
          );
        } else {
          return Container(
            child: Text('sorry you data is not found'),
          );
        }
      });
}

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