First flutter app. Trying to call a method from widget home screen - flutter

I took an application from the internet using flutter_google_maps plugin. To this I added a method called centermap. I have tried countless things to try and get the app to read centermap and relocate the google map to the coordinates. I have tried googling but can't find any examples of doing this in Flutter.
Can some help to get me going. In the orginal code I copied the raised button works.
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
GoogleMapController mapController;
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Google Maps demo')),
body: MapsDemo(),
),
));
centerMap(mapController);
}
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
#override
Widget build(BuildContext context) {
return Padding (
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: SizedBox(
width: 400.0,
height: 500.0,
child: GoogleMap(
onMapCreated: _onMapCreated,
),
),
),
RaisedButton(
child: const Text('Go to London'),
onPressed: mapController == null ? null : (){
mapController.animateCamera(CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
));
},
),
],
),
);
}
void _onMapCreated(GoogleMapController controller) {
setState(() {
mapController = controller;
});
}
}
void centerMap(GoogleMapController mapController) {
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(37.4219999, -122.0862462), zoom: 20.0),
),
);
}

I should have kept trying a few more minutes
This seems to work
void _onMapCreated(GoogleMapController controller) {
setState(() {
mapController = controller;
});
centerMap(mapController);
}
}
void centerMap(GoogleMapController mapController) {
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(37.4219999, -122.0862462), zoom: 20.0),
),
);
}

Related

Flutter not showing CircularProgressIndicator

I'm developing simple webview applicatoin using flutter , here i used CircularProgressIndicator but its not showing.
Package i use: https://pub.dev/packages/flutter_webview_plugin
How i can show the loading using CircularProgressIndicator in flutter ?, I'm using stack to show the loading indicator the centor of it.
class _MyHomePageState extends State<MyHomePage> {
final flutterWebViewPlugin = FlutterWebviewPlugin();
bool isLoading = true;
double webProgress = 0;
#override
void initState() {
super.initState();
flutterWebViewPlugin.onProgressChanged.listen((double progress) {
setState(() {
this.webProgress = progress;
});
print("The progress is $progress");
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: WillPopScope(
onWillPop: () async {
print("back pressed");
return false;
},
child: Stack(
children: [
Column(
children: [
webProgress < 1
? SizedBox(
height: 5,
child: LinearProgressIndicator(
value: webProgress,
color: Colors.blue,
backgroundColor: Colors.white,
),
)
: SizedBox(),
Expanded(
child: WebviewScaffold(
url: "https://google.com",
mediaPlaybackRequiresUserGesture: false,
withLocalStorage: true,
),
),
],
),
isLoading
? Center(
child: CircularProgressIndicator(
color: Colors.red,
),
)
: Stack(),
],
),
),
));
}
}

Flutter animation controller using GetX

I recently switch to GetX and want to init animation controller in GetxController and can access it in GetView. When app started animation gets to go without any problem but can not forward it again.
class SplashController extends GetxController with GetTickerProviderStateMixin {
var h = 0.0.obs;
late AnimationController ac;
late Animation animation;
Future<void> initAnimation() async {
ac = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
animation = Tween(begin: 0.0, end: 1.0).animate(ac);
}
forwardAnimationFromZero() {
ac.forward(from: 0);
}
#override
void onInit() {
super.onInit();
initAnimation();
forwardAnimationFromZero();
ac.addListener(() {
h.value = animation.value;
});
}
#override
void onReady() {
super.onReady();
forwardAnimationFromZero();
}
#override
void onClose() {
super.onClose();
ac.dispose();
}
}
As you see I extended GetxController with GetTickerProviderStateMixin but The ticker not work properly.
I define var h = 0.0.obs; as observable so can access in screen and without it animation does not tick!
class SplashPage extends GetView<SplashController> {
const SplashPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var c = Get.put(SplashController());
return Scaffold(
body: Column(
children: [
Container(
color: Colors.amber,
width: (controller.animation.value * 100) + 100,
height: (controller.animation.value * 100) + 100,
child: Center(
child: Text(
controller.animation.value.toString(),
),
),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
c.ac.forward(from: 0);
},
child: Icon(Icons.refresh),
),
appBar: AppBar(
title: const Text('Splash Page'),
),
);
}
}
in this view when started animation does not react but when I hot relaod i see it in end state.
when change the Container widget to:
Obx(
() => Container(
color: Colors.amber,
width: (controller.animation.value * 100) + 100,
height: (controller.h.value * 100) + 100,
child: Center(
child: Text(
controller.animation.value.toString(),
),
),
),
),
respet to ac.addListener(() {h.value = animation.value;}); animation play at the beginning but can't forward again from zero when I press floatingActionButton.
What I want:
Why animation does not paly at the beginning without h observable?
How can I access animation controller functions in the view?
When some animation controller complete I want to start another animation controller.
Use AnimatedContainer in this part. Because writing too long will slow down your work as the code grows.
Controller
class SplashController extends GetxController {
var h = 40.0.obs;
}
Page
class SplashPage extends GetView<SplashController> {
var click = true;
#override
Widget build(BuildContext context) {
return GetBuilder<SplashController>(
init: Get.put(SplashController()),
builder: (cnt) {
return Center(
child: PageView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ElevatedButton(
child: Text('Animate!'),
onPressed: () {
click
? cnt.h.value = 250.0
: cnt.h.value = 50.0;
click = !click;
},
),
Obx(
() => AnimatedContainer(
duration: Duration(seconds: 1),
width: cnt.h.value,
height: 40,
color: Colors.red,
),
),
],
)
],
),
);
}
);
}
}
The following code is used to update your code when it is a StatelessWidget.
Obx(
() => AnimatedContainer(
duration: Duration(seconds: 1),
width: cnt.h.value,
height: 40,
color: Colors.red,
),
),
Each time you click the button, you will be able to zoom in and out.

Dart/Flutter not changing page with Inkwell and Gesture detector

I am trying to use Inkwell or Gesture detector to navigate to page 2, but it is saying "Undefined name 'context'". Hope someone can help! :))
It is a google maps stack container and other group of containers on the top. When click on the containers on top, it redirects to the 2page.
Main.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'woocommerce/woocommerce_api.dart';
void main() {
runApp(Page1());
}
class Page1 extends StatelessWidget {
//********************************** GOOGLE MAPS *****************************************
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MapView(),
);
}
}
class MapView extends StatefulWidget {
#override
_MapViewState createState() => _MapViewState();
}
class _MapViewState extends State<MapView> {
CameraPosition _initialLocation = CameraPosition(target: LatLng(0.0, 0.0));
GoogleMapController mapController;
final Geolocator _geolocator = Geolocator();
Position _currentPosition;
#override
void initState() {
super.initState();
_getCurrentLocation();
}
_getCurrentLocation() async {
await _geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((Position position) async {
setState(() {
// Store the position in the variable
_currentPosition = position;
print('CURRENT POS: $_currentPosition');
// For moving the camera to current location
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(position.latitude, position.longitude),
zoom: 13.0,
),
),
);
});
}).catchError((e) {
print(e);
});
}
#override
Widget build(BuildContext context) {
// Determining the screen width & height
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
//********************************** GOOGLE MAPS SCREEN **********************************
return Container(
height: height,
width: width,
child: Scaffold(
body: Stack(
children: <Widget>[
GoogleMap(
initialCameraPosition: _initialLocation,
myLocationEnabled: true,
myLocationButtonEnabled: false,
mapType: MapType.normal,
zoomGesturesEnabled: true,
zoomControlsEnabled: false,
onMapCreated: (GoogleMapController controller) {
mapController = controller;
},
),
ClipOval(
child: Material(
color: Color(0xffeb5c68), // button color
child: InkWell(
splashColor: Color(0xffda1b2b), // inkwell color
child: SizedBox(
width: 56,
height: 56,
child: Icon(Icons.my_location),
),
onTap: () {
mapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(
_currentPosition.latitude,
_currentPosition.longitude,
),
zoom: 13.0,
),
),
);
},
),
),
),
//********************************** ORDERS **********************************
Container(
padding: EdgeInsets.only(top: 550, bottom: 50),
child: ListView(
padding: EdgeInsets.only(left: 20),
children: getTechniciansInArea(),
scrollDirection: Axis.horizontal,
),
),
],
)
),
);
}
List<Technician> getTechies() {
List<Technician> techies = [];
//For esting...
// for (int i = 0; i < 10; i++) {
//Technician myTechy = Technician(name:'Apotheken', phoneNum: 'Address store');
Technician myTechy = Technician("Store name test", "Address store ", "Address costumer", 529.3, 4, "Available", "fdfd");
techies.add(myTechy);
//}
return techies;
}
List<Widget> getTechniciansInArea() {
List<Technician> techies2 = getTechies();
List<Widget> cards = [];
for (Technician techy in techies2) {
cards.add(technicianCard(techy));
}
return cards;
}
}
Widget technicianCard(Technician technician) {
return
InkWell( // when click...
child:
Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.only(right: 20),
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 0.5,
),],
),
child:
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 5,),
Text(technician.name, style: TextStyle(fontSize: 19,fontWeight: FontWeight.bold), textAlign: TextAlign.center),
SizedBox(height: 10,),
Text("AS: " + technician.phoneNum, style: TextStyle(fontSize: 15)),
SizedBox(height: 10,),
Text("AC: " + technician.address, style: TextStyle(fontSize: 15)),
SizedBox(height: 30,),
],
),
GestureDetector(
child:
Container(
alignment: Alignment.bottomCenter,
width: 120.0,
height: 40.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
color: Color(0xffeb5c68),
),
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("REQUEST", textAlign: TextAlign.center,style: TextStyle(color: Colors.white),),
]
)
),
onLongPress: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Page2()),
);
},
)
]
)
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Page2()),
);
}
);
}
//********************************** PAGE 2 **********************************
class Page2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Your orders"),
),
);
}
Woocommerce_api.dart:
class Technician {
String name;
String phoneNum;
String address;
double rate;
String status;
int rating;
String occupation;
Technician(this.name, this.phoneNum, this.address, this.rate, this.rating, this.status, this.occupation);
//Technician({this.name, this.phoneNum, this.address, this.rate, this.rating, this.status, this.occupation});
}
You need to send BuildContexti to function. does not see the correct context. likewise, you need to add it to the top. Set the context no matter where you called.
Widget technicianCard(Technician technician, BuildContext context)//add here
{
.....
...
..
}

Can not switch to another page

Here is two classes, that I use, and I want to go from home.dart to map.dart
I need to be working that FlatButton, where onPressed is MapPage();
I also tried to add MaterialApp, because anything I have seen is done with that, but I didn't understood how and what is wrong with all of that. StreaProvider I need for the Firebase, so I can't remove this.
Please, help, if you know how. I really need just to switch to a new page
home.dart
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:notifier_app/models/locationCoordinates.dart';
import 'package:notifier_app/screens/map_page/map.dart';
import 'package:notifier_app/services/auth.dart';
import 'package:notifier_app/services/database.dart';
import 'package:provider/provider.dart';
import 'package:notifier_app/screens/home/coordinates_list.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
/*final MapPage _mapPage = MapPage();*/
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Image.asset(
"assets/homeBackGround.jpg",
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
StreamProvider<List<LocationCoordinates>>.value(
value: DatabaseService().coordinatesOfGPS,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text('Notifier'),
backgroundColor: Colors.transparent,
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.map),
label: Text('Map'),
textColor: Colors.black54,
onPressed: () {
MapPage();
},
),
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('Logout'),
textColor: Colors.black54,
onPressed: () async {
await _auth.signOut();
},
),
],
),
body: CoordinatesList(),
),
),
],
);
}
}
map.dart
import 'dart:async';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
class MapPage extends StatefulWidget {
#override
_MapPageState createState() => _MapPageState();
}
class _MapPageState extends State<MapPage> {
Completer<GoogleMapController> _controller = Completer();
static const LatLng _center = const LatLng(45.5231563, -122.677433);
final Set<Marker> _markers = {};
LatLng _lastMapPosition = _center;
MapType _currentMapType = MapType.normal;
static final CameraPosition _position1 = CameraPosition(
bearing: 192.833,
target: LatLng(45.531563, -122.677433),
tilt: 59.440,
zoom: 11.0,
);
Future<void> _goToPosition1() async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(_position1));
}
_onMapCreated(GoogleMapController controller){
_controller.complete(controller);
}
_onCameraMove(CameraPosition position){
_lastMapPosition = position.target;
}
_onMapTypeButtonPressed() {
_currentMapType =
_currentMapType == MapType.normal ? MapType.satellite : MapType.normal;
}
_onAddMarkerButtonPressed() {
setState(() {
_markers.add(Marker(
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition,
infoWindow: InfoWindow(
title: 'This is a Title',
snippet: 'This is a snippet',
),
icon: BitmapDescriptor.defaultMarker,
));
});
}
Widget button(Function function, IconData icon){
return FloatingActionButton(
onPressed: function,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.blue,
child: Icon(
icon,
size: 36.0,
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Google Map'),
backgroundColor: Colors.blue,
),
body: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom:11.0,
),
mapType: _currentMapType,
markers: _markers,
onCameraMove: _onCameraMove,
),
Padding(
padding: EdgeInsets.all(16.0),
child: Align(
alignment: Alignment.topRight,
child: Column(
children: <Widget>[
button(_onMapTypeButtonPressed, Icons.map),
SizedBox(
height: 16.0,
),
button(_onAddMarkerButtonPressed, Icons.add_location),
SizedBox(
height: 16.0,
),
button(_goToPosition1, Icons.location_searching),
],
),
),
)
],
),
),
);
}
}
You have to use Navigator class to go to the new page. You cannot use Map().
Try calling this:
To Go To New Page
Navigator.push(context,MaterialPageRoute(builder:(context)=>Map());
To Remove this page and return to Previous
Navigator.pop(context);

How to display map when i call screen

I have been using map_view: ^0.0.14 plugin to display map in flutter. Mapview.show() method does not return widget. It returns void So i can call show() method and display map. I want to display map When page loads. How can i do that.
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Google Maps'),
),
body: new Center(
child: Container(
child: RaisedButton(
child: Text('Tap me'),
color: Colors.blue,
textColor: Colors.white,
elevation: 7.0,
onPressed: ( ) {
mapView.show(
new MapOptions(
mapViewType: MapViewType.normal,
showMyLocationButton: true,
showCompassButton: true,
showUserLocation: true,
initialCameraPosition: new CameraPosition(new Location(11.6643, 78.1460), 14.0),
title: 'Google Map'));
},
),
),
),
);
}
As far as I can tell map_view doesn't have a widget.
You can give google_maps_flutter a try, which has a widget that let's you do things like pan or zoom through a controller.
You'll first need to specify your API key in your app's manifest (Android):
<manifest ...
<application ...
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR KEY HERE"/>
or the app delegate (iOS):
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:#"YOUR KEY HERE"];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
#end
On iOS you'll also have to add a boolean to your Info.plist with the key io.flutter.embedded_views_preview and the value YES.
Then you can add the GoogleMap widget to your widget tree:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Google Maps demo')),
body: MapsDemo(),
),
));
}
class MapsDemo extends StatefulWidget {
#override
State createState() => MapsDemoState();
}
class MapsDemoState extends State<MapsDemo> {
GoogleMapController mapController;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: GoogleMap(
onMapCreated: _onMapCreated,
),
),
),
RaisedButton(
child: const Text('Go to London'),
onPressed: mapController == null ? null : () {
mapController.animateCamera(CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
));
},
),
],
),
);
}
void _onMapCreated(GoogleMapController controller) {
setState(() { mapController = controller; });
}
}