Программирование флаттера - PullRequest
0 голосов
/ 24 апреля 2020

ниже приведен код, и я хочу вызвать метод 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);
                  },
                )
            ),
          ],
        ),
      ),
    );
  }
}

1 Ответ

0 голосов
/ 24 апреля 2020

Видите ли, есть n возможностей, в которых вы можете выполнить требование, но самое главное, насколько эффективно вы пишете код для достижения чего-либо.

Чтобы использовать метод getLocation() из home.dart вместо определения метода в самом home.dart, make a separate file, call it helper.dart, а затем импортировать файл на любую страницу Вы хотите

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)));
    });
});

Пожалуйста, прочитайте о том, как использовать Future Class , чтобы узнать больше об этом. Если вы хотите получить дополнительные разъяснения.

Значение - это не что иное, как возвращаемое значение из вашего метода getLocation(). Будущий метод вызывается с then(), так как он сначала выполняет операцию, а затем возвращает значение

Дайте мне знать, если вы не понимаете концепцию или любую проблему, с которой сталкиваетесь. Счастливого обучения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...