hello I try to use google map plugin for flutter https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter
I use this exemple
https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter/example/lib
but in this exemple there is some page. In my application I need only one map at the launch on the app. Problem, with this exemple I didn't manage to use it at my convenience. So I try to use the minimalist example of the read.me but it's a statlesswidget, and I and can't integer Tag fonction or the map_ui.dart like the complet example. So I tried to pass this stateless in statefull but when I do this I have an error
here is what I tried to compile from the two example
exemple 1 https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter
void main() {
GoogleMapController.init();
final GoogleMapOverlayController controller =
GoogleMapOverlayController.fromSize(width: 300.0, height: 200.0);
final Widget mapWidget = GoogleMapOverlay(controller: controller);
runApp(MaterialApp(
home: new Scaffold(
appBar: AppBar(title: const Text('Google Maps demo')),
body: MapUiBody(mapWidget, controller.mapController),
),
navigatorObservers: <NavigatorObserver>[controller.overlayController],
));
}
exemple 2
https://github.com/flutter/plugins/blob/master/packages/google_maps_flutter/example/lib/map_ui.dart
class MapUiBody extends StatefulWidget {
final GoogleMapOverlayController controller;
const MapUiBody(this.controller, GoogleMapController mapController);
#override
State<StatefulWidget> createState() =>
MapUiBodyState(controller.mapController);
}
class MapUiBodyState extends State<MapUiBody> {
MapUiBodyState(this.mapController);
final GoogleMapController mapController;
#override
Widget build(BuildContext context) {
return Column(
);
}
}
with this, I have an error
body: MapUiBody(mapWidget, controller.mapController),
mapWidget: the argument type Widget can't be assigned to the parameter type 'GooglemapoverlayController'
You have
final GoogleMapOverlayController controller;
const MapUiBody(this.controller, GoogleMapController mapController);
where you pass
final GoogleMapOverlayController controller =
GoogleMapOverlayController.fromSize(width: 300.0, height: 200.0);
final Widget mapWidget = GoogleMapOverlay(controller: controller);
...
body: MapUiBody(mapWidget, controller.mapController),
where mapWidget is passed to final GoogleMapOverlayController controller; which is not a Widget.
controller.mapController is probably a GoogleMapController as expected by const MapUiBody(..., GoogleMapController mapController);
but it seems redundant to pass that because you can get it from controller passed to mapWidget anyway.
It's not clear from your code what your intentions are.
Why do you want to pass mapWidget? What should happen with it in MapUiBody?
I succeeded to display map on home page but I can't move the map ..
void main() {
GoogleMapController.init();
final GoogleMapOverlayController controller =
GoogleMapOverlayController.fromSize(width: 300.0, height: 200.0);
final Widget mapWidget = GoogleMapOverlay(controller: controller);
runApp(MaterialApp(
home: new Scaffold(
appBar: AppBar(title: const Text('Google Maps demo')),
body: MapsDemo(mapWidget, controller.mapController),
),
));
}
class MapsDemo extends StatelessWidget {
MapsDemo(this.mapWidget, this.controller);
final Widget mapWidget;
final GoogleMapController controller;
#override
final GoogleMapOverlayController mapController =
GoogleMapOverlayController.fromSize(
width: 300.0,
height: 200.0,
options: GoogleMapOptions(
cameraPosition: const CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
),
trackCameraPosition: true,
),
);
#override
Widget build(BuildContext context) {
return MapUiBody(mapController);
}
}
class MapUiBody extends StatefulWidget {
final GoogleMapOverlayController controller;
const MapUiBody(this.controller);
#override
State<StatefulWidget> createState() =>
MapUiBodyState(controller.mapController);
}
class MapUiBodyState extends State<MapUiBody> {
MapUiBodyState(this.mapController);
final GoogleMapController mapController;
GoogleMapOptions _options;
#override
void initState() {
super.initState();
mapController.addListener(_onMapChanged);
_extractMapInfo();
}
void _onMapChanged() {
setState(() {
_extractMapInfo();
});
}
void _extractMapInfo() {
_options = mapController.options;
}
#override
void dispose() {
mapController.removeListener(_onMapChanged);
super.dispose();
}
Widget _mapTypeCycler() {
final MapType nextType =
MapType.values[(_options.mapType.index + 1) % MapType.values.length];
return FlatButton(
child: Text('change map type to $nextType'),
onPressed: () {
mapController.updateMapOptions(
GoogleMapOptions(mapType: nextType),
);
},
);
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: GoogleMapOverlay(controller: widget.controller),
),
),
Column(
children: <Widget>[
_mapTypeCycler(),
],
),
],
);
}
}
Related
I am trying to read a local json file named "catalog.json" I wrote all the nessessary codes but it's showing this error "lateinitializationError: Field 'catalogdata' has not been initialized."
then i tried by initializing the 'catalogdata' variable but then it shows that 'catalogdata' variable is empty . I dont know how to solve it . Please help me.
my code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
late List catalogdata;
Future<String> loadData() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
setState(() {
catalogdata = json.decode(data);
});
return "success";
}
#override
void initState() {
// TODO: implement initState
this.loadData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Homepage"),
),
body: Center(
child: Text(
catalogdata[0],
style: TextStyle(fontSize: 20),
),
),
);
}
}
Here’s sample.json:
{
"items": [
{
"id": "p1",
"name": "Item 1",
"description": "Description 1"
},
{
"id": "p2",
"name": "Item 2",
"description": "Description 2"
},
{
"id": "p3",
"name": "Item 3",
"description": "Description 3"
}
]
}
The code which is used to fetch data from the JSON file (see the full code below):
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
// ...
}
Declare the json file in the assets section in your pubspec.yaml file:
flutter:
assets:
- assets/sample.json
main.dart
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List _items = [];
// Fetch content from the json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
setState(() {
_items = data["items"];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Kindacode.com',
),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
ElevatedButton(
child: const Text('Load Data'),
onPressed: readJson,
),
// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["id"]),
title: Text(_items[index]["name"]),
subtitle: Text(_items[index]["description"]),
),
);
},
),
)
: Container()
],
),
),
);
}
}
it's showing this error "lateinitializationError: Field 'catalogdata'
has not been initialized." then I tried by initializing the
'catalogdata'
While using late before variables make sure that, the variable must be initialized later. Otherwise, you can encounter a runtime error when the variable is used.
If you didn't add the correct location catalog.json in pubsec.yaml your variable catalog didn't gets the correct value so the late variable is not initialized.
So you must add asset path in pubsec.yaml
assets:
- assets/
- assets/images/files/catalog.json
Another case here is JSON.decode() return map<string,dynamic> value here you set list.maybe that also cause the problem and not initialised.
instead of this late List catalogdata; use this late var catalogdata; or late Map<string,dynamic> catalogdata;
Sample Code
Catalog.json
{
"name": "lava",
"Catagory": "man"
}
Main.dart
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class AppRoutes {
static String detail = "/Detail";
static String Page2 = "/FilterBeacon";
static String Page1 = "/FilterPoint";
static String home = "/";
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
// key: constItem.navigatorKey,
initialRoute: "/",
routes: {
AppRoutes.home: (context) => Home(),
},
title: _title,
// home: ,
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
var _index = 0;
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Homepage(),
);
}
}
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
late var catalogdata;
Future<String> loadDatas() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
// setState(() {
catalogdata = json.decode(data);
// });
return "success";
}
Future<String> loadData() async {
var data = await rootBundle.loadString("assets/images/files/catalog.json");
setState(() {
catalogdata = json.decode(data);
});
return "success";
}
#override
void initState() {
loadData();
// loadData().then((value) => catalogdata=value);
} // String jsons = "";
// #override
// Future<void> initState() async {
// super.initState();
// await loadData();
// }
#override
Widget build(BuildContext context) {
var futureBuilder = FutureBuilder(
future: loadData(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.connectionState == ConnectionState.done)
return Center(
child: Text(
catalogdata.toString(),
style: TextStyle(),
),
);
else
return Container();
});
return Scaffold(
appBar: AppBar(
title: Text("Homepage"),
),
body: Center(
child: Text(
catalogdata.toString(),
style: TextStyle(),
),
),
);
}
}
I've implemented this code to show a list of json data from a web url.
I've tried to implement a simple pull to refresh, but nothing works.
Flutter code is long, but it's pretty simple actually. It has main classes of flutter, and a future method to load json data from web.
I just want to implement a simple pull to refresh.
What am I missing here?
Why is it not working?
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pull_to_refresh/pull_to_refresh.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'XXX',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'XXX'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final RefreshController _refreshController = RefreshController();
Future<List<User>> _getUsers() async {
var data = await http.get("xxxxxxxxxxxxx");
if (data.statusCode == 200) {
print('Status Code 200: Ok!');
var jsonData = json.decode(data.body);
List<User> users = [];
for (var k in jsonData.keys) {
var u = jsonData[k];
//print(u["pubdate"]);
User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"], u["img"], u["pubdate"]);
users.add(user);
}
print(users.length);
return users;
} else {
throw Exception('Failed to load json');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SmartRefresher(
controller: _refreshController,
enablePullDown: true,
header: WaterDropHeader(),
onRefresh: () async {
await Future.delayed(Duration(seconds: 1));
_refreshController.refreshCompleted();
},
child: FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data == null){
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int id){
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[id].img
),
),
title: Text(snapshot.data[id].title),
subtitle: Column(
children: <Widget>[
Row(
children: [
Text(
snapshot.data[id].source,
overflow: TextOverflow.fade,
maxLines: 1,
softWrap: false,
),
Spacer(),
Text(snapshot.data[id].pubdate),
],
),
],
)
);
},
);
}
},
),
),
);
}
}
class User {
final int id;
final String source;
final String desc;
final String link;
final String title;
final String img;
final String pubdate;
User(this.id, this.source, this.desc, this.link, this.title, this.img, this.pubdate);
}
Solved!
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'XXXX',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'XXXXXX'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//Funcao para buscar as noticias
Future<List<User>> _getUsers() async {
var data = await http.get("XXXXX");
if (data.statusCode == 200) {
print('Status Code 200: Ok!');
var jsonData = json.decode(data.body);
List<User> users = [];
for (var k in jsonData.keys) {
var u = jsonData[k];
//print(u["pubdate"]);
User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"], u["img"], u["pubdate"]);
users.add(user);
}
print(users.length);
return users;
} else {
throw Exception('Failed to load json');
}
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
refreshList();
}
Future<Null> refreshList() async {
refreshKey.currentState?.show(atTop: false);
await Future.delayed(Duration(seconds: 2));
setState(() {
_getUsers();
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: RefreshIndicator(
key: refreshKey,
child: FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data == null){
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int id){
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[id].img
),
),
title: Text(snapshot.data[id].title),
subtitle: Column(
children: <Widget>[
Row(
children: [
Text(
snapshot.data[id].source,
overflow: TextOverflow.fade,
maxLines: 1,
softWrap: false,
),
Spacer(),
Text(snapshot.data[id].pubdate),
],
),
],
)
);
},
);
}
},
),
onRefresh: refreshList,
),
);
}
}
class User {
final int id;
final String source;
final String desc;
final String link;
final String title;
final String img;
final String pubdate;
User(this.id, this.source, this.desc, this.link, this.title, this.img, this.pubdate);
}
You have to get users on onLoading as shown below
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SmartRefresher(
....
onLoading: _getUsers,
.....
)
}
i have a class that call it in main class but i want pass a function to sub class and run function to sub class and return response of function to main class how to do in flutter dart.
Do
class subclassName
final function NameOfFunction;
subclassName(this.NameOfFunction);
in main class
subclassName(the function you want to pass);
main
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
void _answerQuestion() {
setState(() {
_questionIndex = _questionIndex + 1;
});
print(_questionIndex);
}
#override
Widget build(BuildContext context) {
print("object");
var questions = [
{
'questionText':'What\'s your favorite color?',
'answers': ['Black','Red','Green','White'],
},
{
'questionText':'What\'s your favorite animal?',
'answers': ['Rabbit','Snak','Elephant','Lion'],
},
{
'questionText':'who\'s your favorite instructor?',
'answers': ['suhaib','max','khalid','moh'],
}
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
questions[_questionIndex]['questionText'],
),
...(questions[_questionIndex]['answers'] as List<String>).map((answer){
return Answer(_answerQuestion, answer);
}).toList(),
],
),
),
);
}
}
sub class
class Answer extends StatelessWidget {
final String textanswer;
final Function answerQuestion;
Answer(this.answerQuestion,this.textanswer);
#override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(textanswer),
onPressed: answerQuestion,
),
);
}
}
As the title has said, whenever I run the flutter application in my phone (debug mode atm, I don't know if it will work correctly in release mode). The dndguide.toString() appears as null. However, upon a hot reload the string appears normally. Is there a way to avoid this and make it work correctly upon launching? I suspect I put the loadjson() call in the wrong location, but I've tried shaping the code so that the function is called in different areas and no success.
Here is the code for the application:
import 'package:flutter/material.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
void main() => runApp(MyApp());
var dndguide;
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<String> _loadAsset() async {
return await rootBundle.loadString('assets/data/HDARG.json');
}
Future loadjson() async {
String jsonString = await _loadAsset();
final jsonResponse = json.decode(jsonString);
dndguide = jsonResponse;
}
#override
Widget build(BuildContext context) {
loadjson();
var scrollcontroller;
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: MediaQuery.of(context).size.height - 24,
margin: EdgeInsets.only(top: 24.0),
width: MediaQuery.of(context).size.width * .90,
child: SingleChildScrollView(
physics: BouncingScrollPhysics(),
controller: scrollcontroller,
scrollDirection: Axis.vertical,
child: Text(dndguide.toString()),
),
),
],
),
),
);
}
}
The json response is called asynchronously, which why the first time it gives null and after hot reloading it appears successfully. You should put some placeholder value into your dndguide variable or call the json in the initState() function of your _MyHomePageState instead of calling it during build process:
#override
void initState() {
super.initState();
loadjson();
}
In my flutter app. I am using google_maps_plugin . The link is https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter .
I want to fix the marker in center of map without moving of icon after drag the map. I successfully done by using stack . But my question is how to get the longitude and latitude of icon I placed in stack .
I want it likes http://jsfiddle.net/UuDA6/
The code is shown below.
class MyApp extends StatelessWidget {
MyApp();
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Title',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new AppPage(title: 'Augr'),
);
}
}
class AppState extends InheritedWidget {
const AppState({
Key key,
this.mode,
Widget child,
}) : assert(mode != null),
assert(child != null),
super(key: key, child: child);
final Geocoding mode;
static AppState of(BuildContext context) {
return context.inheritFromWidgetOfExactType(AppState);
}
#override
bool updateShouldNotify(AppState old) => mode != old.mode;
}
class AppPage extends StatefulWidget{
AppPage() : super(key: key);
#override
_AppPageState createState() => new _AppPageState();
}
class _AppPagePageState extends State<MyApp> {
_AppPagePageState();
List<Address> results = [];
String address;
String googleMapsApiKey = 'APIKEY';
GoogleMapController mapController;
Position position;
#override
Widget build(BuildContext context){
return new Scaffold(
appBar: null,
body: Padding(
padding: EdgeInsets.only(top: 25.0),
child:Column(
children: <Widget>[
SizedBox(
width: 200,
height: 300,
child: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
),
InfoView()
],
),
),],
)
),
);
}
void initState() {
super.initState();
}
void _onMapCreated(GoogleMapController controller) {
setState(() {
mapController = controller;
mapController.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 270.0,
target: LatLng(lattitude, longitude),
tilt: 30.0,
zoom: 17.0,
),
));
});
}
}
class InfoView extends StatelessWidget {
const InfoView({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Align(
alignment: Alignment.center,
child: new Icon(Icons.person_pin_circle, size: 40.0), //This the icon showing in google map .
);
}
}
The infoView() is defined the icon to show overlap in google map. I want to fetch the latitude and longitude of the icon place in map.
If any one have the idea about it please share it.