Flutter 天气应用程序中的城市选择 - Flutter

city selection in flutter weather app - Flutter

希望你一切顺利 我是 flutter 的新手,我正在开发一个基本的天气应用程序作为初学者。现在,不知何故一切都很好,除了城市名称。我不知道如何实现城市搜索功能并根据位置从 api 获取数据。在我的代码中,我手动定义了城市名称。 这是我的代码:

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:hava_chitor/Carousel.dart';
import 'package:hava_chitor/UnderCarousel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var temp;
  var name;
  var humidity;
  var description;
  var city = 'London';

  CarouselController buttonCarouselController = CarouselController();

  Future getWeather() async {
    http.Response response = await http.get(
        "http://api.openweathermap.org/data/2.5/weather?q=$city&units=metric&appid=apikey");
    var results = jsonDecode(response.body);
    setState(() {
      this.temp = results['main']['temp'];
      this.name = results['name'];
      this.humidity = results['main']['humidity'];
      this.description = results['weather'][0]['main'];
    });
  }

  @override
  void initState() {
    super.initState();
    this.getWeather();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hava Chitor?',
      theme: ThemeData(
        primaryColor: Color(0xff424242),
      ),
      home: Scaffold(
        drawer: Drawer(),
        appBar: AppBar(
          actions: [
            Padding(
              padding: const EdgeInsets.all(15),
              child: GestureDetector(
                onTap: () {
                  print('kir');
                },
                child: Icon(
                  Icons.add_circle_outline,
                  color: Color(0xff5d5f64),
                ),
              ),
            )
          ],
          backgroundColor: Colors.transparent,
          elevation: 0,
          iconTheme: IconThemeData(color: Color(0xff5d5f64)),
          title: Text(
            'Hava Chitor?',
            style: TextStyle(
                color: Color(0xff5d5f64),
                fontFamily: 'Sans',
                fontWeight: FontWeight.w700),
          ),
          centerTitle: true,
        ),
        backgroundColor: Colors.white,
        body: Padding(
          padding: const EdgeInsets.symmetric(vertical: 1.0),
          child: Column(
            children: [
              Carousel(name),
              UnderCarousel(temp, description, humidity),
            ],
          ),
        ),
      ),
    );
  }
}

您需要添加一个 TextField 和一个 TextFieldController,并在用户写完城市名称时调用函数 getWeather,类似这样

  String city;
  TextEditingController textEditingController = TextEditingController();

TextField(
  controller: textEditingController,
  onSubmitted: (value){
    city = textEditingController.text;
    getWeather();
  },
),

您需要做的是添加TextField 供用户输入城市名称。 你可以这样做的方式如前所述。接下来你要做的是编写一个函数来获取带有城市名称的天气数据。

var url =
    'http://api.openweathermap.org/data/2.5/weather?q=$city&units=metric&appid=apikey';

class CityWeatherData {
  final String city, temprateure, humidity; //...

  CityWeatherData({
    this.city,
    this.temprateure,
    this.humidity,
    // ...
  });

  factory CityWeatherData.fromJson(Map<String, dynamic> json) {
    return CityWeatherData(
      city: json['city'],
      humidity: json['city']['humidity'],
      temprateure: json['city']['temp'],
      // ...
    );
  }
}

Future<CityWeatherData> fetchWeatherDataBycity() async {
  final response = await http.get(url);
  if (response.statusCode == 200) {
    return CityWeatherData.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('failed to fetch data.');
  }
}

根据您获得的 JSON 数据,您必须编辑 fromjson 方法。

希望对您有所帮助!