【问题标题】:city selection in flutter weather app - FlutterFlutter 天气应用中的城市选择 - Flutter
【发布时间】:2020-12-04 12:20:01
【问题描述】:

希望你做得好 我是一个新手,我正在开发一个基本的天气应用程序作为初学者。现在,不知何故一切都好,除了城市名称。我不知道如何实现城市搜索功能并根据位置从 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),
            ],
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

标签: android api flutter openweathermap weather-api


【解决方案1】:

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

  String city;
  TextEditingController textEditingController = TextEditingController();

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

【讨论】:

    【解决方案2】:

    您需要做的是添加 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 方法。

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      相关资源
      最近更新 更多