我每次都必须使用 ctrl+s 来更新 UI 。设置状态()不工作。在哪里正确使用 setstate()?

I have to use ctrl+s everytime to updatde UI . Setstate() not working. Where to use setstate() properly?

我正在写一个天气应用程序的代码,只有两个屏幕。我正在使用 openWeatherApi 使用 http 协议从互联网上存在的 json 文件中获取天气数据,以获取我的天气 UI。现在的问题是,来自 json 的数据完美地到达了终端,但是 在我按下 ctrl+s.The [=66] 之前它不会到达 UI 屏幕=] 直到我按下 ctl+S 才会更新。当我第一次运行代码时它不显示当前天气状态(以摄氏度为单位),它只显示空值,屏幕上写的空值,应该显示当前天气,并且图像也表现得像那样。现在我没有得到 is a setstate() issue 或其他。我不知道为什么 UI 不是 updating.I 而是 提供 我正在使用的每个文件 。请帮忙!.

Flutter 医生

[√] Flutter (Channel stable, 2.5.1, on Microsoft Windows [Version 10.0.19041.1237], locale en-PK)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.60.2)
[√] Connected device (2 available)

• No issues found!

pubspec.yaml

name: weather_ui
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3


  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter


# The following section is specific to Flutter.
flutter:

 
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
     - assets/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

main.dart

import 'package:flutter/material.dart';
import 'package:weather_ui/UI/getstarted.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(debugShowCheckedModeBanner: false, home: GetStarted());
  }
}

getstart.dart(用户按下按钮并移动到第二个屏幕的第一个屏幕)

import 'package:flutter/material.dart';
import 'package:weather_ui/UI/weather_page.dart';

class GetStarted extends StatefulWidget {
  const GetStarted({Key? key}) : super(key: key);

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

class _GetStartedState extends State<GetStarted> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [
                  Colors.blueGrey,
                  Colors.black,
                ],
                begin: Alignment.bottomLeft,
                end: Alignment.topRight,
                stops: [0, 1]),
          ),
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 180),
                height: 170,
                width: 170,
                child: Image.asset('assets/cloud2.png'),
              ),
              Container(
                margin: EdgeInsets.only(top: 150, left: 70),
                child: Row(
                  children: [
                    Text(
                      'Weather',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 40,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text(
                      'News',
                      style: TextStyle(
                          color: Colors.yellow,
                          fontSize: 40,
                          fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
              Text(
                '& Feed',
                style: TextStyle(
                    fontSize: 40,
                    fontWeight: FontWeight.bold,
                    color: Colors.yellow),
              ),
              Container(
                margin: EdgeInsets.all(10),
                padding: EdgeInsets.all(5),
                child: Text(
                  'Thinking About Weather Cicumstances!.Get Notified With Latest Weather Updates Here',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.w400),
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(
                height: 10,
              ),
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      primary: Colors.yellow,
                      onPrimary: Colors.black,
                      padding: EdgeInsets.all(15),
                      minimumSize: Size(320, 0),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15))),
                  onPressed: () {
                    //startApp();
                    Navigator.pushReplacement(context,
                        MaterialPageRoute(builder: (builder) => WeatherPage()));
                  },
                  child: Text('Get start',
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.bold)))
            ],
          ),
        ),
      ),
    );
  }
}

weather_page.dart(我显示数据的第二个或主屏幕,UI 未更新。)

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:weather_ui/UI/getstarted.dart';
import 'package:weather_ui/UI/weatherApidata.dart';

class WeatherPage extends StatefulWidget {
  const WeatherPage({Key? key}) : super(key: key);

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

class _WeatherPageState extends State<WeatherPage> {
  void startApp() async {}

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
    ApiData instance = ApiData(location: 'Lahore');
    instance.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        leading: InkWell(
          child: Icon(Icons.ac_unit),
          onTap: () {
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (builder) => GetStarted()));
          },
        ),
        backgroundColor: Colors.blueGrey,
        elevation: 0,
        title: Text(
          'Weather Forcast',
          textAlign: TextAlign.center,
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.blueGrey, Colors.black],
                begin: Alignment.bottomLeft,
                end: Alignment.topRight,
                stops: [1, 1]),
          ),
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(children: [
            // ClipRRect(
            //   borderRadius: BorderRadius.circular(40),
            //Expanded(
            currentWeather(),

            SizedBox(
              height: 25,
            ),
            nextSevenDaysForcast(),

            alldayforcaast(),

            Row(
              children: [
                SizedBox(
                  width: 15,
                ),
                Text(
                  'Chance of Rain',
                  style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ],
            ),

            todayWeatherGraph(),
          ]),
        ),
      ),
      // ),
    );
  }

  Container todayWeatherGraph() {
    return Container(
        padding: EdgeInsets.all(5),
        margin: EdgeInsets.only(top: 10, right: 10, left: 10, bottom: 20),
        height: 200,
        width: 400,
        decoration: BoxDecoration(
          color: Colors.transparent,
          // border: Border.all(width: 1, color: Colors.white10),
          //borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child: Column(
          children: [
            Row(
              children: [
                Column(
                  children: [
                    Text(
                      'Rainy',
                      style: TextStyle(
                          color: Colors.white60,
                          fontWeight: FontWeight.bold,
                          fontSize: 15),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Text(
                      'Sunny',
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Text('Heavy',
                        style: TextStyle(
                            color: Colors.white60,
                            fontWeight: FontWeight.bold,
                            fontSize: 15)),
                  ],
                ),
                Column(
                  children: [
                    Image.asset(
                      'assets/graph2.jpg',
                      width: 323,
                    )
                  ],
                )
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              children: [
                SizedBox(
                  width: 60,
                ),
                Text(
                  '10 AM',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.white),
                ),
                SizedBox(
                  width: 25,
                ),
                Text(
                  '12 AM',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.white),
                ),
                SizedBox(
                  width: 25,
                ),
                Text('02 PM',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    )),
                SizedBox(
                  width: 25,
                ),
                Text('05 PM',
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.white)),
                SizedBox(
                  width: 25,
                ),
                Text('07 PM',
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.white)),
              ],
            )
          ],
        ));
  }

  Container nextSevenDaysForcast() {
    return Container(
      child: Row(
        children: [
          SizedBox(
            width: 20,
          ),
          Text(
            'Today',
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.yellow,
                fontSize: 20),
          ),
          SizedBox(
            width: 20,
          ),
          Text(
            'Tomorrow',
            style: TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20),
          ),
          SizedBox(
            width: 20,
          ),
          Text(
            'Next 7 Days',
            style: TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20),
          ),
        ],
      ),
    );
  }

  Container alldayforcaast() {
    return Container(
      height: 200,
      width: double.infinity,
      //margin: EdgeInsets.only(top: 20, left: 10, right: 10),
      padding: EdgeInsets.all(4),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '10 AM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '26',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '12 AM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '27',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '02 PM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '28',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
    ],
      ),
    );
  }

  Container currentWeather() {
    //Map map = ModalRoute.of(context).settings.arguments;
    var t = ApiData.temprature;
    var uicon = ApiData.uiicon;
    setState(() {});

    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.all(20),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                'Today',
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white),
              ),
              SizedBox(
                width: 170,
              ),
              Text(
                'Thur, 30 Sep',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.bold),
              )
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              RichText(
                  text: TextSpan(
                      //style: DefaultTextStyle.of(context).style,

                      text: t.toString().substring(0, 2),
                      style: TextStyle(
                          fontSize: 60,
                          fontWeight: FontWeight.bold,
                          color: Colors.white),
                      children: [
                    TextSpan(
                        text: '°C',
                        style: TextStyle(
                          color: Colors.yellow,
                          fontSize: 30,
                        ))
                  ])),
              SizedBox(
                width: 120,
              ),
              Image.network(
                "http://openweathermap.org/img/wn/$uicon@2x.png",
              ),
            ],
          ),
          SizedBox(
            height: 40,
          ),
          Row(
            children: [
              Icon(
                Icons.location_on,
                color: Colors.orange,
              ),
              SizedBox(
                width: 5,
              ),
              Text(
                'MuslimTown,Lahore',
                style: TextStyle(color: Colors.white, fontSize: 20),
              )
            ],
          )
        ],
      ),
      height: 250,
      width: 370,
      decoration: BoxDecoration(
        color: Colors.white10,
        // border: Border.all(width: 1, color: Colors.white10),
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
    );
  }
}

weatherApidata.dart(这里使用http获取数据url)

import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiData {
  String? location;
  //named constructor for the value of location in  URL
  ApiData({this.location}) {
    location = this.location;
  }

  static double? temprature;
  String? description;
  Map? main;
  static String? uiicon;

  Future<void> getData() async {
    final String uri =
        "https://api.openweathermap.org/data/2.5/weather?q=$location&appid=2128fd6e36b66857a8329a16ea0bf00f";
    final Uri url = Uri.parse(uri);
    final response = await http.get(url);
    Map data = jsonDecode(response.body);

    Map temprature_data = data['main'];
    temprature = temprature_data['temp'] - 273.15;

    List weather_data = data['weather'];
    Map weather_main_data = weather_data[0];
    Map main_description = data['main'];
    String getdescription = weather_main_data['description'];
    uiicon = weather_main_data['icon'];

    int pressure = temprature_data['pressure'];

    description = getdescription;
    main = main_description;
    print(main);
    print(uiicon);
    print(description);
    print((temprature).toString().substring(0, 4));
    print(pressure);
  }
}

你没有在正确的地方调用 setState,setstate 应该在你从 api 中检索到数据后调用,这里是你如何在 weather_page.dart 中解决这个问题:

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:weather_ui/UI/getstarted.dart';
import 'package:weather_ui/UI/weatherApidata.dart';

class WeatherPage extends StatefulWidget {
  const WeatherPage({Key? key}) : super(key: key);

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

class _WeatherPageState extends State<WeatherPage> {
  void startApp() async {}

  @override
  void initState() {

    super.initState();
    fetchWeatherData();
  }

  Future fetchWeatherData() async
  {
    ApiData instance = ApiData(location: 'Lahore');
    await instance.getData();
    setState(() {});

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        leading: InkWell(
          child: Icon(Icons.ac_unit),
          onTap: () {
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (builder) => GetStarted()));
          },
        ),
        backgroundColor: Colors.blueGrey,
        elevation: 0,
        title: Text(
          'Weather Forcast',
          textAlign: TextAlign.center,
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.blueGrey, Colors.black],
                begin: Alignment.bottomLeft,
                end: Alignment.topRight,
                stops: [1, 1]),
          ),
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(children: [
            // ClipRRect(
            //   borderRadius: BorderRadius.circular(40),
            //Expanded(
            currentWeather(),

            SizedBox(
              height: 25,
            ),
            nextSevenDaysForcast(),

            alldayforcaast(),

            Row(
              children: [
                SizedBox(
                  width: 15,
                ),
                Text(
                  'Chance of Rain',
                  style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ],
            ),

            todayWeatherGraph(),
          ]),
        ),
      ),
      // ),
    );
  }

  Container todayWeatherGraph() {
    return Container(
        padding: EdgeInsets.all(5),
        margin: EdgeInsets.only(top: 10, right: 10, left: 10, bottom: 20),
        height: 200,
        width: 400,
        decoration: BoxDecoration(
          color: Colors.transparent,
          // border: Border.all(width: 1, color: Colors.white10),
          //borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child: Column(
          children: [
            Row(
              children: [
                Column(
                  children: [
                    Text(
                      'Rainy',
                      style: TextStyle(
                          color: Colors.white60,
                          fontWeight: FontWeight.bold,
                          fontSize: 15),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Text(
                      'Sunny',
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    Text('Heavy',
                        style: TextStyle(
                            color: Colors.white60,
                            fontWeight: FontWeight.bold,
                            fontSize: 15)),
                  ],
                ),
                Column(
                  children: [
                    Image.asset(
                      'assets/graph2.jpg',
                      width: 323,
                    )
                  ],
                )
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              children: [
                SizedBox(
                  width: 60,
                ),
                Text(
                  '10 AM',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.white),
                ),
                SizedBox(
                  width: 25,
                ),
                Text(
                  '12 AM',
                  style: TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.white),
                ),
                SizedBox(
                  width: 25,
                ),
                Text('02 PM',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    )),
                SizedBox(
                  width: 25,
                ),
                Text('05 PM',
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.white)),
                SizedBox(
                  width: 25,
                ),
                Text('07 PM',
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.white)),
              ],
            )
          ],
        ));
  }

  Container nextSevenDaysForcast() {
    return Container(
      child: Row(
        children: [
          SizedBox(
            width: 20,
          ),
          Text(
            'Today',
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.yellow,
                fontSize: 20),
          ),
          SizedBox(
            width: 20,
          ),
          Text(
            'Tomorrow',
            style: TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20),
          ),
          SizedBox(
            width: 20,
          ),
          Text(
            'Next 7 Days',
            style: TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20),
          ),
        ],
      ),
    );
  }

  Container alldayforcaast() {
    return Container(
      height: 200,
      width: double.infinity,
      //margin: EdgeInsets.only(top: 20, left: 10, right: 10),
      padding: EdgeInsets.all(4),
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '10 AM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '26',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '12 AM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '27',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: 150,
              margin: EdgeInsets.all(10),
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 80, top: 10),
                        height: 50,
                        width: 50,
                        child: Image.asset(
                          'assets/cloud2.png',
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 7, left: 10),
                        child: Text(
                          '02 PM',
                          style: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15, left: 10),
                        child: RichText(
                            text: TextSpan(
                                text: '28',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 30),
                                children: [
                              TextSpan(
                                  text: '°C',
                                  style: TextStyle(
                                      color: Colors.yellow,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20))
                            ])),
                      )
                    ],
                  )
                ],
              ),
              decoration: BoxDecoration(
                color: Colors.white10,
                // border: Border.all(width: 1, color: Colors.white10),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
            ),
          ),
    ],
      ),
    );
  }

  Container currentWeather() {
    //Map map = ModalRoute.of(context).settings.arguments;
    var t = ApiData.temprature;
    var uicon = ApiData.uiicon;

    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.all(20),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                'Today',
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white),
              ),
              SizedBox(
                width: 170,
              ),
              Text(
                'Thur, 30 Sep',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.bold),
              )
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              RichText(
                  text: TextSpan(
                      //style: DefaultTextStyle.of(context).style,

                      text: t.toString().substring(0, 2),
                      style: TextStyle(
                          fontSize: 60,
                          fontWeight: FontWeight.bold,
                          color: Colors.white),
                      children: [
                    TextSpan(
                        text: '°C',
                        style: TextStyle(
                          color: Colors.yellow,
                          fontSize: 30,
                        ))
                  ])),
              SizedBox(
                width: 120,
              ),
              Image.network(
                "http://openweathermap.org/img/wn/$uicon@2x.png",
              ),
            ],
          ),
          SizedBox(
            height: 40,
          ),
          Row(
            children: [
              Icon(
                Icons.location_on,
                color: Colors.orange,
              ),
              SizedBox(
                width: 5,
              ),
              Text(
                'MuslimTown,Lahore',
                style: TextStyle(color: Colors.white, fontSize: 20),
              )
            ],
          )
        ],
      ),
      height: 250,
      width: 370,
      decoration: BoxDecoration(
        color: Colors.white10,
        // border: Border.all(width: 1, color: Colors.white10),
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
    );
  }
}

我还建议您阅读有关 StatefulWidget 的更多信息,并避免使用静态字段来保存应用程序的状态。

在编辑代码以删除对 DataApi 静态字段的依赖的过程中,您应该按如下方式更改 DataApi class:

import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiData {
  String? location;
  //named constructor for the value of location in  URL
  ApiData({this.location}) {
    location = this.location;
  }

  double? temprature;
  String? description;
  Map? main;
  String? uiicon;

  Future<void> getData() async {
    final String uri =
        "https://api.openweathermap.org/data/2.5/weather?q=$location&appid=2128fd6e36b66857a8329a16ea0bf00f";
    final Uri url = Uri.parse(uri);
    final response = await http.get(url);
    Map data = jsonDecode(response.body);

    Map temprature_data = data['main'];
    temprature = temprature_data['temp'] - 273.15;

    List weather_data = data['weather'];
    Map weather_main_data = weather_data[0];
    Map main_description = data['main'];
    String getdescription = weather_main_data['description'];
    uiicon = weather_main_data['icon'];

    int pressure = temprature_data['pressure'];

    description = getdescription;
    main = main_description;
    print(main);
    print(uiicon);
    print(description);
    print((temprature).toString().substring(0, 4));
    print(pressure);
  }
}

然后在有状态的小部件中,添加一个 ApiData 属性 作为小部件状态的一部分,无论您在哪里使用静态字段,都可以将它们替换为 ApiData 实例的字段如下:

为这样的状态添加 ApiData 属性 :

class _WeatherPageState extends State<WeatherPage> {

  ApiData apiData = ApiData(location: 'Lahore'); 

像这样更改 fetchWeatherData 函数以使用 getData 的实例:

  Future fetchWeatherData() async
  {
    await instance.getData();
    setState(() {
    });

  }

然后通过编辑 currentWeather 函数在小部件构建中使用它:

  Container currentWeather() {
    //Map map = ModalRoute.of(context).settings.arguments;
    var t = apiData.temprature;
    var uicon = apiData.uiicon;

请注意,为了 post 的简单性,我保持代码简短,只向您展示了您需要应用的修改。