翩翩计划

下面是给定的代码,我想调用方法。getLocation() 的档案 home.dart 镖档 addLoc.dart ,特别是,我想叫 getLocation() 的方法

           Container(
            height: 50,
            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            child: RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              child: Text('Use my current location'),
              onPressed: () {
                Navigator.pop(context);
              },
            )
        ),

位于 addLoc.dart.

这些文件如下。

home.dart

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void mapCreated(controller) {
    setState(() {
      _controller = controller;
    });
  }
  List<Marker> allMarkers = [];
  GoogleMapController _controller;
  var pose;
  @override
  void initState() {
    super.initState();
    allMarkers.add(Marker(
        markerId: MarkerId('mk1'),
        draggable: false,
        onTap: () {
          print('Marker Tapped');
        },
        position: LatLng(21.2205, 72.8750)));
    allMarkers.add(Marker(
        markerId: MarkerId('mk2'),
        draggable: false,
        onTap: () {
          print('Marker Tapped');
        },
        position: LatLng(21.1897, 72.8270)));
  }

  Future<void> getLocation() async{
    final pose = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
    setState(() {
      allMarkers.add(Marker(
          markerId: MarkerId('myLoc'),
          draggable: false,
          onTap: () {
            print('Marker Tapped');
          },
          position: LatLng(pose.latitude,pose.longitude)));
    });
    return pose;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fire & Emergency'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.account_circle),
            onPressed: () {
              Navigator.pushNamed(context, '/login');
            },
          ),
        ],
      ),
      body: Stack(children: [
        Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: GoogleMap(
            initialCameraPosition:
                CameraPosition(target: LatLng(21.1702, 72.8311), zoom: 12.0),
            markers: Set.from(allMarkers),
            onMapCreated: mapCreated,
          ),
        ),
        Container(
          alignment: Alignment.bottomLeft,
          padding: EdgeInsets.fromLTRB(10, 0, 0, 10),
          child: FloatingActionButton(
            heroTag: "btn1",
            child: Tooltip(
              message: 'add new location',
              child: Icon(
                Icons.gps_fixed,
                color: Colors.grey[800],
              ),
            ),
            backgroundColor: Colors.brown[50],
            onPressed: () {
              getLocation();
            },
          ),
        ),
        Container(
          alignment: Alignment.bottomLeft,
          padding: EdgeInsets.fromLTRB(10, 0, 0, 80),
          child: FloatingActionButton(
            heroTag: "btn2",
              child: Tooltip(
                message: 'add new location',
                child: Icon(
                  Icons.location_on,
                  color: Colors.grey[800],
                  size: 30,
                ),
              ),
            backgroundColor: Colors.brown[50],
            onPressed: () {
              Navigator.pushNamed(context, '/addLoc');
            },
          ),
        ),
      ]),
    );
  }
}

addLoc.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'home.dart';

// ignore: camel_case_types
class addLoc extends StatefulWidget{
  @override
  _addLocState createState() => _addLocState();
}
// ignore: camel_case_types
class _addLocState extends State<addLoc> {
  MyHomePage mhp=new MyHomePage();
  TextEditingController LongCont = TextEditingController();
  TextEditingController LattCont = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fire & Emergency'),
      ),
      body:Container(
        child: ListView(
          children: <Widget>[
            Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(10),
                child: Text(
                  'Add New Location',
                  style: TextStyle(fontSize: 20,color: Colors.blue),
                )
            ),
            Container(
              padding: EdgeInsets.all(10),
              child: TextField(
                controller: LongCont,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Longitude',
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(10),
              child: TextField(
                controller: LattCont,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Lattitude',
                ),
              ),
            ),
            Container(
                height: 50,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.blue,
                  child: Text('Add New'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                )
            ),
            Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(10),
                child: Text(
                  'Or',
                  style: TextStyle(fontSize: 15,color: Colors.blue),
                )
            ),
            Container(
                height: 50,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.blue,
                  child: Text('Use my current location'),
                  onPressed: () {

                    Navigator.pop(context);
                  },
                )
            ),
          ],
        ),
      ),
    );
  }
}

解决方案:

你看,有N多种可能性可以实现需求,但最重要的是你如何高效地写代码来实现一些东西。

为了利用 getLocation() 方法从 home.dart的方法,而不是在 home.dart 本身。make a separate file, call it helper.dart 然后将文件导入到任何你想要的页面中。

帮助者.飞镖

import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class Helper{
  // If you are returning something out of the future class, try giving a 
  // dynamic if you are confused of the datatype it returns
  static Future<dynamic> getLocation() async{
    final pose = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
    return pose;
  }
}

然后导入该文件,并像这样在任何地方使用它。

import helper.dart

// This is how you call the method from Helper class
Helpers.getLocation().then((value){
   //your operation
   setState(() {
      allMarkers.add(Marker(
          markerId: MarkerId('myLoc'),
          draggable: false,
          onTap: () {
            print('Marker Tapped');
          },
          position: LatLng(value.latitude,value.longitude)));
    });
});

请阅读关于如何使用 未来班 以获得更多的见解。如果你想得到更多的澄清。

Value不过是你的 getLocation() 方法。以后的方法都用 then(),因为它首先执行操作,然后返回值。

如果你有不懂的概念或者遇到什么问题,请告诉我。快乐学习

给TA打赏
共{{data.count}}人
人已打赏
未分类

用户输入修改结束日期的倒计时器。

2022-9-8 17:03:17

未分类

VLC VLCJ流密码保护无用武之地

2022-9-8 17:03:19

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索