如何在flutter中使用geoLocator软件包在控制台上打印当前位置?

时间:2020-10-29 14:23:40

标签: flutter dart location emulation

这是我在loading_screen.dart文件中的代码。我已经明确提到要打印我的位置,甚至在onpressed中调用该方法。仍然没有回应。

var portName = process.argv[2];
var dato = process.argv[3];

var SerialPort = require("serialport");
var Readline = require('@serialport/parser-readline');
var serialport = new SerialPort(portName, { baudRate: 115200 });
   // Look for return and newline at the end of each data packet
var parser = serialport.pipe(new Readline({ delimiter: '\n' }));

serialport.on('open', function(err) {
    // A timeout is necessary to wait the port to open (if not working, try to 
   increase the milliseconds value)
    setTimeout(function() {
        serialport.write(dato);
    }, 1700);
    if(err) {
        console.log('Error when trying to open:' + err);
    }
    parser.on('data', function(data) {
        console.log(data);
        serialport.close(function (err) {
           if(err){
                console.log('port closed', err);
            }
         });
     });
 });

serialport.on('close', () => {
 console.log('Bye');
});

1 个答案:

答案 0 :(得分:0)

实施中缺少几个步骤。

首先,您需要检查权限,如果允许,请获取位置,否则请寻求权限。

对于Android,您还需要在清单中添加权限;对于iOS,还需要在info.plist中添加权限

示例代码:-

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Test(),
    );
  }
}

class Test extends StatefulWidget{
  @override
  _Test createState() => _Test();
}

class _Test extends State<Test>{

  void getLocation() async{
    LocationPermission permission = await Geolocator.checkPermission();
    if(permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
      printLocation();
    }else{
      requestPermission();
    }
  }

  requestPermission() async{
    LocationPermission permission = await Geolocator.requestPermission();
    if(permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
      printLocation();
    }else{
      requestPermission();
    }
  }

  printLocation() async{
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low, timeLimit: Duration(seconds: 10));
    print(position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}