У меня есть нижеследующее, которое отлично работает для получения текущего местоположения и его отображения:
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:simple_permissions/simple_permissions.dart';
import 'babies.dart';
class LocationState extends State {
String _location_text;
Location _location = new Location();
Map<String, double> _currentLocation;
String error;
@override
void initState() {
super.initState();
setState(() {
_location_text = 'Clik to update location';
});
}
// Platform messages are asynchronous, so we initialize in an async method.
_getLocation() async {
Map<String, double> location;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
await SimplePermissions.requestPermission(Permission.AccessFineLocation);
location = await _location.getLocation();
error = null;
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
} else if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error =
'Permission denied - please ask the user to enable it from the app settings';
}
location = null;
}
print("error $error");
setState(() {
_currentLocation = location;
_location_text = ('${_currentLocation["latitude"]}, ${_currentLocation["longitude"]}' ?? 'Grant location Access');
print(_currentLocation);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Baby Name Votes')),
body: _buildBody(context),
);
}
Widget _buildBody(BuildContext context) {
return
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ButtonTheme.bar(
child: ButtonBar(
children: <Widget>[
Text.rich(
TextSpan(text: '$_location_text'),
),
FlatButton(
child: const Icon(Icons.my_location),
onPressed: () {
_getLocation();
var alt = _currentLocation["latitude"];
print(
"my $alt at location is: $_currentLocation");
},
)
])
),
]),
),
],
),
),
Expanded(
child: MyCustomListViewWidget(),
),
],
);
}
}
Я бы хотел упростить виджет до:
Widget _buildBody(BuildContext context) {
return
Column(
children: <Widget>[
MyLocationWidget(),
Expanded(child: MyCustomListViewWidget(),),
],
);
}
Итак, я написал MyLocationWidget
, как показано ниже, но столкнулся с проблемой получения ошибки undefined name
для всех функций / параметров, связанных с state
, таких как _getLocation()
, $_currentLocation
, $_location_text
:
import 'package:flutter/material.dart';
import 'location.dart';
class MyLocationWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ButtonTheme.bar(
child: ButtonBar(
children: <Widget>[
Text.rich(
TextSpan(text: '$_location_text'),
),
FlatButton(
child: const Icon(Icons.my_location),
onPressed: () {
_getLocation();
var alt = _currentLocation["latitude"];
print(
"my $alt at location is: $_currentLocation");
},
)
])
),
]),
),
],
),
);
}
}
Итак, у меня вопрос, как определить эти переменные в пользовательском виджете, чтобы они плавно обменивались данными с state