我的flutter应用程序有一个小问题。我无法在屏幕上打印位置值。应该怎么办?

问题描述 投票:0回答:1

我正在尝试创建一个扑朔迷离的天气应用。这是我第一次创建应用程序并学习编码。到目前为止,这很好,但是我有一个小问题。我无法在屏幕上打印或显示位置。 İt应该位于设备屏幕的顶部。

当我在模拟器上运行该应用程序时,它确实显示了设备的当前位置。但是,当我在物理设备(OnePlus 5和Galaxy S10)上运行该应用程序时,它没有显示位置。

正如您将在下面看到的,我也无法将该位置打印到控制台中。

我有2个.dart文件。下面提供了两个文件中的代码。

除此以外,一切正常。没有错误显示。

我缺少什么或做错了什么。感谢您的帮助。

main.dart:

import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'GetLocation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

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

class AuraWeather extends StatefulWidget {
  @override
  _AuraWeatherState createState() => _AuraWeatherState();
}

class _AuraWeatherState extends State<AuraWeather> {

  var apiKey = '******************************';
  var description;
  var city;
  var maxTemp;
  var minTemp;
  var temp;

  @override
  Widget build(BuildContext context) {
    getLocation();

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(displayBackground()),
          ),
        ),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaY: 2, sigmaX: 2),
          child: Container(
            color: Colors.black.withOpacity(0.5),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              body: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      Container(
                        child: Center(
                          child: Text(
                            '$city',
                            style: TextStyle(
                              fontSize: 35,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        child: Icon(
                          FontAwesomeIcons.locationArrow,
                          color: Colors.white,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 80),
                        child: Text(
                          '$temp' + '°',
                          style: TextStyle(
                              fontSize: 50,
                              color: Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 30),
                    child: Icon(
                      Icons.wb_sunny,
                      color: Colors.white,
                      size: 100,
                    ),
                  ),
                  Container(
                    child: Center(
                      child: Text(
                        '$maxTemp ° | $minTemp °',
                        style: TextStyle(fontSize: 20, color: Colors.white),
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      '$description',
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ),
                  ),
                  Container(
                    child: FlatButton(
                      child: Icon(
                        Icons.refresh,
                        color: Colors.white,
                        size: 40,
                      ),
                      color: Colors.transparent,
                      onPressed: () {
                        setState(
                          () {
                            getLocation();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // display background images based on current time
  displayBackground() {
    var now = DateTime.now();
    final currentTime = DateFormat.jm().format(now);
    if (currentTime.contains('AM')) {
      return 'images/Blood.png';
    } else if (currentTime.contains('PM')) {
      return 'images/Sun.png';
    }
  }

  //getLocation
  void getLocation() async {
    Getlocation getlocation = Getlocation();
    await getlocation.getCurrentLocation();

    print(getlocation.latitude);
    print(getlocation.longitude);
    print(getlocation.city);
    city = getlocation.city;
    getTemp(getlocation.latitude, getlocation.longitude);
  }

  //Get current temp
  Future<void> getTemp(double lat, double lon) async {
    http.Response response = await http.get(
        'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
    //print(response.body);

    var dataDecoded = jsonDecode(response.body);
    description = dataDecoded['weather'][0]['description'];

    temp = dataDecoded['main']['temp'];
    temp = temp.toInt();

    maxTemp = dataDecoded['main']['temp_max'];
    maxTemp = maxTemp.toInt();

    minTemp = dataDecoded['main']['temp_min'];
    minTemp = minTemp.toInt();

    print(temp);
  }
}

GetLocation.dart:

import 'package:geolocator/geolocator.dart';

class Getlocation {
    double latitude;
    double longitude;
    String city;
    //Get current location
    Future<void> getCurrentLocation() async {
        try {
            Position position = await Geolocator()
                    .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
            latitude = position.latitude;
            longitude = position.longitude;

            city = await getCityName(position.latitude, position.longitude);
        } catch (e) {
            print(e);
        }
    }

    //Get city name
    Future<String> getCityName(double lat, double lon) async {
        List<Placemark> placemark =
        await Geolocator().placemarkFromCoordinates(lat, lon);
        print('city name is: ${placemark[0].locality}');
        return placemark[0].locality;
    }
}

控制台窗口:

Performing hot reload...
Syncing files to device ONEPLUS A5000...
Reloaded 0 of 587 libraries in 251ms.
I/flutter (13296): city name is: 
I/flutter (13296): 41.0179339
I/flutter (13296): 28.6239036
I/flutter (13296): 
I/flutter (13296): 20

Pubspec:

name: com
description: A new Flutter application.

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number

     separated by a +.
    # Both the version and the builder number may be overridden in flutter
    # build by specifying --build-name and --build-number, respectively.
    # In Android, build-name is used as versionName while build-number used as versionCode.
    # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
    # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
    # Read more about iOS versioning at
    # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
    version: 1.0.0+1

    environment:
      sdk: ">=2.1.0 <3.0.0"

    dependencies:
      flutter:
        sdk: flutter

      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^0.1.2
      intl: ^0.16.1
      geolocator: ^5.3.1
      http: ^0.12.0+4
      sunrise_sunset: ^1.0.2
      font_awesome_flutter: ^8.5.0

    dev_dependencies:
      flutter_test:
        sdk: flutter


    # For information on the generic Dart part of this file, see the
    # following page: https://dart.dev/tools/pub/pubspec

    # The following section is specific to Flutter.
    flutter:

      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true

      # To add assets to your application, add an assets section, like this:
      assets:
        - images/
      #  - 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

AndroidManifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.auraweather">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="auraweather"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
flutter dart weather
1个回答
0
投票

它似乎是不错的代码,但是这里没有东西。

首先:您的位置许可请求在哪里?第二:为什么不使用initState进行覆盖

getLocation();

并且在最后一步,您必须实现Geolocator插件的所有要求。

检查这些步骤并在评论中更新我。

© www.soinside.com 2019 - 2024. All rights reserved.