i have created a map view with google_maps_flutter 1.0.2 in my flutter app and i'm setting 3 different custom markers on my mapview. two of them are set using a check box but i want to show first set of custom markers when the app first started up. with this code i can set the marker when i first launch the app but marker icon is default one(red baloon like icon) not my custom icon but if i tap the check box twice i'll get the markers with my icon. i tried even using after_layout library fix this issue but no luck.
import 'dart:async';
import 'package:expandable_bottom_sheet/expandable_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:location/location.dart';
import 'package:after_layout/after_layout.dart';
class RoadAssistance extends StatefulWidget {
#override
_RoadAssistanceState createState() => _RoadAssistanceState();
}
class _RoadAssistanceState extends State<RoadAssistance>
with AfterLayoutMixin<RoadAssistance> {
Completer<GoogleMapController> _controller = Completer();
CameraPosition _currentPosition = CameraPosition(
target: LatLng(6.9147, 79.9729),
zoom: 15.4746,
);
Set<Marker> markers = Set();
Set<Marker> markers1 = Set();
bool askingPermission = false;
bool showGarages = false;
bool showBranches = true;
bool firstTime = true;
LocationData _locationData;
BitmapDescriptor myPosIcon;
BitmapDescriptor branchIcon;
BitmapDescriptor garageIcon;
#override
void initState() {
super.initState();
BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(55, 55)), 'images/me.png')
.then((onValue) {
myPosIcon = onValue;
});
BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(55, 55)), 'images/home-city.png')
.then((onValue) {
branchIcon = onValue;
});
BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(48, 48)), 'images/wrench.png')
.then((onValue) {
garageIcon = onValue;
});
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
var padding = MediaQuery.of(context).padding;
return Scaffold(
appBar: AppBar(
title: Text('Road Assitance'),
backgroundColor: Color.fromRGBO(0, 172, 192, 100),
),
body: ExpandableBottomSheet(
background: Stack(children: [
SizedBox(
height: height - 130,
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: _currentPosition,
myLocationEnabled: true,
myLocationButtonEnabled: true,
markers: markers,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
),
Container(
padding: EdgeInsets.all(5),
width: width,
height: height - 240,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black38.withOpacity(0.6),
spreadRadius: 1,
blurRadius: 4,
offset:
Offset(0, 3), // changes position of shadow
),
],
),
width: 160,
padding: EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 30.0,
width: 30.0,
child: Checkbox(
value: showBranches,
onChanged: (bool newValue) {
newValue
? loadBranches()
: unloadBranches();
setState(() {
showBranches = newValue;
print(newValue);
});
}),
),
Icon(
MdiIcons.homeCity,
color: Colors.green[700],
),
SizedBox(
width: 5,
),
Text(
'Branches',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
)
],
),
),
SizedBox(
height: 10,
),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black38.withOpacity(0.6),
spreadRadius: 1,
blurRadius: 4,
offset:
Offset(0, 3), // changes position of shadow
),
],
),
width: 160,
padding: EdgeInsets.all(5),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 30.0,
width: 30.0,
child: Checkbox(
value: showGarages,
onChanged: (bool newValue) {
newValue ? loadGarages() : unloadGarages();
setState(() {
showGarages = newValue;
print(newValue);
});
}),
),
Icon(
MdiIcons.hammerWrench,
color: Colors.orange[700],
),
SizedBox(
width: 5,
),
Text(
'Garages',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
)
],
),
),
],
),
],
),
),
]),
),
}
#override
void afterFirstLayout(BuildContext context) {
// Calling the same function "after layout" to resolve the issue.
loadBranches();
print("function called");
}
getLocation() async {
Location location = new Location();
LocationData _locationData1;
bool _serviceEnabled;
PermissionStatus _permissionGranted;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
_locationData1 = await location.getLocation();
print(_locationData1);
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(_currentPosition));
markers.add(
Marker(
markerId: MarkerId('I\'m Here'),
position: LatLng(_locationData1.latitude, _locationData1.longitude),
icon: myPosIcon,
),
);
setState(() {
_currentPosition = new CameraPosition(
target: LatLng(_locationData1.latitude, _locationData1.longitude),
zoom: 15.4746,
);
});
}
loadGarages() {
print("laod garages called");
markers.addAll([
Marker(
markerId: MarkerId('SLIC Garage'),
position: LatLng(6.9217, 79.9739),
infoWindow: InfoWindow(title: 'SLIC Garage New'),
icon: garageIcon,
),
Marker(
markerId: MarkerId('SLIC Garage 2'),
position: LatLng(6.9197, 79.9639),
infoWindow: InfoWindow(title: 'SLIC Garage Nugapityiia'),
icon: garageIcon,
),
Marker(
markerId: MarkerId('SLIC Garage 3'),
position: LatLng(6.9087, 79.9729),
infoWindow: InfoWindow(title: 'SLIC Garage '),
icon: garageIcon,
),
]);
}
unloadGarages() {
print("unlaod garages called");
markers.removeWhere((x) => x.icon == garageIcon);
}
loadBranches() {
print("laod branches called");
markers.addAll([
Marker(
markerId: MarkerId('SLIC Branch'),
position: LatLng(6.9167, 79.9749),
infoWindow: InfoWindow(title: 'SLIC Branch Hewagama'),
icon: branchIcon,
),
Marker(
markerId: MarkerId('SLIC Branch 2'),
position: LatLng(6.9157, 79.9639),
infoWindow: InfoWindow(title: 'SLIC Branch Kotahawala'),
icon: branchIcon,
),
Marker(
markerId: MarkerId('SLIC Branch Malabe'),
position: LatLng(6.9287, 79.9729),
icon: branchIcon,
),
]);
}
unloadBranches() {
if (firstTime) {
markers.clear();
firstTime = false;
return;
}
print("unlaod branches called");
markers.removeWhere((x) => x.icon == branchIcon);
}
}
You can try this:
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
myPosIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(55, 55)), 'images/me.png');
branchIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(55, 55)), 'images/home-city.png');
garageIcon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(48, 48)), 'images/wrench.png');
setState(() {});
});
super.initState();
}
Related
I'm new to flutter.
When I'm trying to add list data to the widget RealAppcard of Text
the list data is '${extractRooms[0]}'
I'm getting this error
RangeError (index): Index out of range: no indices are valid: 0
but without this data added everything is working
what am I doing wrong here?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gs/card_real_app.dart';
import 'package:gs/homescreen.dart';
import 'package:gs/network.dart';
import 'package:gs/pic_model.dart';
import 'package:gs/reusable_card.dart';
import 'package:dotted_border/dotted_border.dart';
import 'Custom_textfield.dart';
import 'order.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'ordertile.dart';
const cardinactiveColor = Color(0xFF0a1529);
const cardActivecolor = Color(0xFFffb700);
var orderData;
// List<Order> orders = <Order>[];
List<Order> OrdersItems = [];
List<dynamic> feedbacks = [];
List<dynamic> pics = [];
late final String? picData;
late final String? statusData;
List<dynamic> filteredOrdersItems = [];
List<dynamic> feedbpics = [];
// final assetController = TextEditingController();
String currentSearch = '';
// String? statusOrder;
// String? picOrder;
// String? myStr = 'shalom';
List<dynamic> extractRooms = [];
List<dynamic> extractStatus = [];
List<dynamic> extractType = [];
List<dynamic> extractMap = [];
dynamic getRooms() {
filteredOrdersItems.forEach((item) {
extractRooms.insert(0, item.rooms);
// print('${item.pic}');
});
}
dynamic getType() {
filteredOrdersItems.forEach((item) {
extractType.insert(0, item.type);
// print('${item.pic}');
});
}
dynamic getSatausData() {
filteredOrdersItems.forEach((item) {
extractStatus.insert(0, item.status);
// print('${item.pic}');
});
}
dynamic getPicData() {
filteredOrdersItems.forEach((item) {
extractMap.insert(0, item.pic);
// print('${item.pic}');
});
}
var data;
var parsedJsonText = jsonDecode(data);
class searchScreen extends StatefulWidget {
// firstScreen({Key? key}) : super(key: key);
#override
State<searchScreen> createState() => _searchScreenState();
}
class _searchScreenState extends State<searchScreen> {
#override
void initState() {
super.initState();
getOrders().then((
OrderItems,
) {
setState(() {
// this.OrderItems = OrderItems;
// filteredOrdersItems = OrderItems;
});
});
}
// void initState() {
// super.initState();
// getOrders().then((
// feedbackItems,
// ) {
// setState(() {
// // this.feedbackItems = feedbackItems;
// // this.filteredFeedbackItems = feedbackItems;
// });
// });
// }
// List<OrderModel> orders = <OrderModel>[];
Color cardColor = cardinactiveColor;
void updateColor() {
if (cardColor == cardinactiveColor) {
cardColor = cardActivecolor;
} else {
cardColor = cardinactiveColor;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// ignore: prefer_const_literals_to_create_immutables
Container(
height: 400,
color: Color(0xFF0a1529),
child: Column(
children: [
const Icon(
Icons.real_estate_agent_outlined,
color: Colors.white,
size: 80,
),
// data: Icons.real_estate_agent_outlined,
SizedBox(height: 5),
Text(
'ברוכים הבאים לאפליקצית חיפוש נכסים',
style: TextStyle(
fontSize: 20.0,
color: Colors.blue,
),
),
SizedBox(height: 15),
CustomTextField(
data: Icons.search,
// controller: null,
hintText: 'חיפוש נכס',
enabled: true,
// controller: assetController,
),
SizedBox(height: 15),
DottedBorder(
color: Color(0xFFffb700),
strokeWidth: 1,
child: Card(
color: Colors.transparent,
elevation: 0,
child: Container(
width: 400,
height: 140,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Padding(
padding: EdgeInsets.all(10.0),
child: Icon(
FontAwesomeIcons.crown,
// Icons.workspace_premium,
color: Color(0xFFffb700),
),
),
Padding(
padding: EdgeInsets.all(10.0),
child: Text(
'מיוחדים',
style: TextStyle(
color: Colors.white,
),
),
),
],
),
Text(
'מוזמנים להתנסות במערכת הנפלאה',
style: TextStyle(
color: Color(0xFF8d8e98),
),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
GestureDetector(
onTap: () {},
child: Card(
color: cardColor,
child: Container(
child: Row(
children: [
ButtonTheme(
minWidth: 30.0,
height: 15.0,
child: RaisedButton(
color: Colors.amber,
child: Text(
'בצעו חיפוש',
style: TextStyle(
fontSize: 20,
),
),
onPressed: () async {
feedbacks = await getOrders();
// pics = await getPic();
// feedbpics =
// pics.where((element) {
// return element.id ==
// currentSearch;
// }).toList();
// print(feedbpics);
print(feedbacks);
filteredOrdersItems =
feedbacks.where((element) {
return element.address ==
currentSearch;
}).toList();
filteredOrdersItems
.forEach((item) {
print('${item.pic}');
});
// picData = getStatus();
// statusData = getPic();
// print('pic $picData');
// print('status $statusData');
// getPic();
getPicData();
getType();
getSatausData();
getRooms();
print(
'checking ${filteredOrdersItems[0]}');
print(
'list map${filteredOrdersItems}');
print('list $extractMap');
print(extractMap[0]);
print(
'status ${extractStatus[0]}');
print(
'rooms ${extractRooms[0]}');
// print(
// 'status ${extractMapStatus}');
setState(() {});
}),
),
// Text(
// 'בדקו עכשיו',
// style: TextStyle(
// color: Colors.white,
// ),
// ),
Icon(
FontAwesomeIcons.arrowRight,
// Icons.workspace_premium,
color: Color(0xFFffb700),
),
],
),
),
),
)
],
),
],
),
),
),
),
],
),
),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
color: Colors.white,
elevation: 5,
child: Container(
width: 500,
height: 500,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(25)),
child: Column(
children: [
// Text('${feedbpics[0]}'),
if (filteredOrdersItems.isEmpty) ...{
Text(
"לא נמצאו תוצאות נסו שנית",
style: TextStyle(
fontSize: 20,
),
),
} else ...{
Text(
'${extractType[0]}',
style: TextStyle(
fontSize: 20,
),
),
SizedBox(height: 20),
Card(
elevation: 8,
child: Image.network(
'${extractMap[0]}',
width: 200,
height: 100,
),
),
},
// SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'כתובת מלאה',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFFA435F0),
),
),
Text('ניקוד נכס'),
],
),
// SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
realAppCard(
text: 'חדרים',
quantity: '${extractRooms[0]}',
),
realAppCard(
text: 'גודל דירה',
quantity: '120',
),
realAppCard(
text: 'מחיר',
quantity: '1.5',
),
],
),
SizedBox(height: 10),
Card(
color: Colors.green,
elevation: 10,
child: Container(
width: 100,
height: 30,
child: Text(
'status',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
),
),
),
),
SizedBox(height: 5),
Center(
child: Text(
'''
הרשות פרסמה את ממצאי התחקיר שערכה על הרג כתבת אל ג'זירה,
ממנו עולה שהחיילים ירו בה בכוונה, למרות שראו שמדובר בעיתונאית.
לטענת התובע, הקליע, שהשימוש בו לא היה חוקי
''',
textAlign: TextAlign.center,
),
),
SizedBox(height: 5),
Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(10),
topRight: Radius.circular(10)),
side: BorderSide(width: 1, color: Colors.blueGrey)),
child: ListTile(
leading: Icon(Icons.message_outlined),
trailing: Text('משה כהן'),
title: Text('052-3567104'),
),
),
SizedBox(height: 5),
ElevatedButton(
onPressed: null,
child: Text('שליחת ווטסאפ'),
),
],
)),
// Center(
// child: Container(
// width: 300,
// child: TextField(
// decoration: const InputDecoration(
// border: OutlineInputBorder(), hintText: 'הקלידו הזמנה'),
// onChanged: (String newstr) {
// currentSearch = newstr;
// // print('first: ${currentSearch}');
// // print(newstr);
// // feedbackItems.forEach((element) {
// // print(element.status);
// // });
// },
// ),
// ),
// ),
// SizedBox(height: 20),
// ButtonTheme(
// minWidth: 200.0,
// height: 30.0,
// child: RaisedButton(
// color: Colors.amber,
// child: Text(
// 'בצעו חיפוש',
// style: TextStyle(
// fontSize: 20,
// ),
// ),
// onPressed: () async {
// feedbacks = await getOrders();
// print(feedbacks);
// filteredOrdersItems = feedbacks.where((element) {
// return element.id == currentSearch;
// }).toList();
// print(filteredOrdersItems);
// setState(() {});
// }),
// ),
// SizedBox(height: 10),
// ignore: sdk_version_ui_as_code
)
],
),
);
}
}
Future<List<dynamic>> getOrders() async {
String url =
'https://script.google.com/macros/s/AKfycbyT3xsBV2nrxgCotCA8-hyZ1DNTNt1ET0wuKilQZr29ac8pbpXMk7nMrCnz2_7NPW1j/exec';
var response = await http.get(Uri.parse(url));
var jsonData = convert.jsonDecode(response.body) as List;
String data = response.body;
// var parsedJson = json.decode(response.body);
// var orderModel = jsonDecode(data)[0]['pic'];
// print('this is my natun ${orderModel}');
// print('response body ${data}');
// print(jsonData);
return jsonData.map((json) => Order.fromJson(json)).toList();
// for (var order in jsonData) {
// OrdersItems.add(Order(order['id'], order['name'], order['status']));
// OrdersItems.forEach((element) {
// print("id : ${element.id}");
// });
// }
// // filteredOrdersItems =
// // OrdersItems.where((ord) => ord['id'] == 'test').toList();
// print(OrdersItems[1].id);
// print(OrdersItems);
// print(filteredOrdersItems);
// return OrdersItems;
}
// Future<List<dynamic>> getPic() async {
// String url =
// 'https://script.google.com/macros/s/AKfycbz12UnYLSmxvwGdeUH2EI7VQ8AnLMACE6IEy3bl3TcmhnyWa0Wmfxxr17swWWXCoXqd/exec';
// var response = await http.get(Uri.parse(url));
// var jsonData = convert.jsonDecode(response.body) as List;
// // print(jsonData);
// return jsonData.map((json) => Pic.fromJson(json)).toList();
// }
if you getting the error, it means one of the extractRoom throwing this is empty, so what you can do it check if the extractRoom is not empty before displaying its content.
realAppCard(
text: 'מחיר',
quantity: extractRoom.isNotEmpty ? extractRoom[0] : '0.0',
),
this will do the work
I am havin this issue where I have a two step form. There is a local JSON file that I load initiating the state to use on the second step in a dropdown widget. However, when I click the continue button and switch to the second form, the variable changes to null causing to get the error "The method 'map' was called on null". I have tried loading the data in the onPressed function of the continueButton Widget, and tried to load again when creating one of the widget of the second form. But I always get this error that the map function was called on null. Help please !!!
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';
import 'package:ofepaw/services/auth.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
class RegisterPage extends StatefulWidget {
final Function toggleView;
RegisterPage({this.toggleView});
#override
State createState() => RegisterPageState();
}
class RegisterPageState extends State<RegisterPage> {
final AuthService _auth = AuthService();
// store the step we are in
int step = 1;
// Text Field
String emailOrPhone = "";
String pass = "";
String verifyPass = "";
String firstName = "";
String lastName = "";
String department = "";
String arrondissement = "";
String commune = "";
// variable for errors
String error = "";
// array containing the forms
var form1;
var form2;
// Controllers for the Textfields
final _emailOrPhoneController = TextEditingController();
final _passwordController = TextEditingController();
final _verifyPassController = TextEditingController();
final _firstNameController = TextEditingController();
final _lastNameController = TextEditingController();
//final _departmentController = TextEditingController();
//load the geographic division of Haiti json file
var division;
// get the locations data
Future<void> loadDivision() async {
String jsonString = await rootBundle
.loadString('assets/haiti_administrative_district.json');
Map<String, dynamic> map = json.decode(jsonString);
List<dynamic> data = map["departments"];
setState(() {
division = data;
});
}
// function to register user in ofepaw database
Future registerUser(
String id, String fname, String lname, String department) async {
final String url = "url go here";
final response = await http.post(url, body: {
"id": id,
"fname": fname,
"lname": lname,
"department": department
});
if (response.statusCode == 201) {
print("This is the response from the server");
print(response.body);
print("Response passed");
} else {
print("Error occured");
}
print(" The response is : ");
print(response.body.toString());
}
//functions for switching forms
getForm(int form) {
if (form == 1) {
return form1;
} else if (form == 2) {
return form2;
}
}
#override
void initState() {
super.initState();
loadDivision();
print(division);
form1 = <Widget>[
firstForm(),
Text("Or Sign Up with social media"),
SizedBox(
height: 20,
),
socialMediaButtons(),
SizedBox(
height: 50,
),
InkWell(
onTap: () {
widget.toggleView();
},
child: Text("Have an account? Login"))
];
form2 = <Widget>[
secondForm(),
InkWell(
//back button
onTap: () => setState(() => step = 1),
child: Text("Back"))
];
}
// dispose all controllers
// dispose of all TextEditingControllers
#override
void dispose() {
_emailOrPhoneController.dispose();
_passwordController.dispose();
_verifyPassController.dispose();
_firstNameController.dispose();
_lastNameController.dispose();
//_departmentController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Material(
child: Expanded(
child: Stack(
children: <Widget>[
// banner with picture
Positioned(
child: banner(),
),
// Login Elements Container
Positioned(
child: Container(
margin: EdgeInsets.only(top: 300.0),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 5,
blurRadius: 20,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.only(
topRight: Radius.circular(50),
topLeft: Radius.circular(50))),
child: Center(
child: Column(
children: getForm(step),
),
),
),
)
],
),
),
);
}
Widget banner() {
return Container(
height: 350,
decoration: BoxDecoration(color: Colors.white),
child: Center(
child: Image.network(
"https://image.freepik.com/free-vector/man-using-his-phone-instead-working_23-2148501890.jpg"),
),
);
}
Widget emailField() {
return TextFormField(
controller: _emailOrPhoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "Email or Phone Number",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => emailOrPhone = val);
},
);
}
Widget firstNameField() {
return TextFormField(
controller: _firstNameController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "First Name",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => firstName = val);
},
);
}
Widget lastNameField() {
return TextFormField(
controller: _lastNameController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "Last Name",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => lastName = val);
},
);
}
Widget departmentField() {
return DropdownButtonFormField(
items: division.map<DropdownMenuItem<String>>((value) {
return DropdownMenuItem<String>(
value: value["name"],
child: Text(value["name"]),
);
}).toList(),
hint: Text("Choose the department"),
onChanged: (value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
);
}
Widget arrondissementField() {
return DropdownButtonFormField(
items: [
DropdownMenuItem(
child: Text("Delmas"),
value: 1,
),
DropdownMenuItem(
child: Text("Petion-Ville"),
value: 2,
)
],
hint: Text("Choose the department"),
onChanged: (int value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)));
}
Widget communeField() {
return DropdownButtonFormField(
items: [
DropdownMenuItem(
child: Text("Delmas"),
value: 1,
),
DropdownMenuItem(
child: Text("Petion-Ville"),
value: 2,
)
],
hint: Text("Choose the department"),
onChanged: (int value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)));
}
Widget passwordField() {
return TextFormField(
controller: _passwordController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 5, left: 20, right: 20),
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => pass = val);
});
}
Widget verifyPasswordField() {
return TextFormField(
controller: _verifyPassController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 5, left: 20, right: 20),
border: InputBorder.none,
hintText: "Reenter Password",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => verifyPass = val);
});
}
Widget socialMediaButtons() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SignInButton(Buttons.Facebook,
mini: true, onPressed: () => print("Facebook Sign in ...")),
SignInButton(Buttons.Google,
//mini: true,
onPressed: () => print("Google Sign in ..."))
],
);
}
Widget continueButton() {
return ButtonTheme(
minWidth: 185.0,
height: 48.0,
child: RaisedButton(
color: Colors.black,
textColor: Colors.white,
child: Text("continue"),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)),
onPressed: () {
print(division);
setState(() {
step = 2;
});
},
));
}
Widget signUpButton() {
return ButtonTheme(
minWidth: 185.0,
height: 48.0,
child: RaisedButton(
color: Colors.black,
textColor: Colors.white,
child: Text("Sign Up"),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)),
onPressed: () async {
dynamic result =
await _auth.registerWithEmailAndPassword(emailOrPhone, pass);
if (result == null) {
setState(() => error = "Email or Password incorrect");
} else {
// Register user ID in the server database
registerUser(result.user.uid, firstName, lastName, department);
}
},
));
}
Widget emailPassField() {
return Container(
// Form input field
margin: EdgeInsets.only(top: 40.0),
width: 320.0,
height: 180.0,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 0.2,
blurRadius: 5,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.circular(20)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
emailField(),
Divider(),
passwordField(),
Divider(),
verifyPasswordField()
],
),
);
}
Widget personalInfoField() {
return Container(
// Form input field
margin: EdgeInsets.only(top: 40.0),
width: 320.0,
height: 310.0,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 0.2,
blurRadius: 5,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.circular(20)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
firstNameField(),
Divider(),
lastNameField(),
Divider(),
departmentField(),
Divider(),
arrondissementField(),
Divider(),
communeField()
],
),
);
}
Widget firstForm() {
return Column(
children: <Widget>[
emailPassField(),
SizedBox(
height: 50,
),
continueButton(),
SizedBox(
height: 50,
),
],
);
}
Widget secondForm() {
return Column(
children: <Widget>[
personalInfoField(),
SizedBox(
height: 40,
),
signUpButton(),
SizedBox(
height: 40,
),
],
);
}
}
The root of your problem starts here String jsonString = await rootBundle.loadString('assets/haiti_administrative_district.json');
Are you sure your project can recognize thise: 'assets/haiti_administrative_district.json'? Have you added it to your assests in pubspec.yaml?
Because this is line is returning null, everything downward will b e returning null, including the error you are reciving.
Future<void> loadDivision() async {
String jsonString = await rootBundle
.loadString('assets/haiti_administrative_district.json');
Map<String, dynamic> map = json.decode(jsonString);
List<dynamic> data = map["departments"];
setState(() {
division = data;
});
}
Here, first make sure data is getting loaded in jsonString.
Second, make sure json.decode(jsonString) is returning json object and not array of json objects.
If it is returning array of json objects, store it in a List<Map>.
Then make a list like this:
List<Map> maps = json.decode(jsonString);
List data=new List();
maps.forEach((element)=>data.add(element['departments']));
I wanted to design a card when clicked it will navigate to a specified marker
I fetched my coordinates (markers) from cloud firestore. everything works perfectly. but when I tried to link my marker with card using pageview.builder it fails.
I already connected and fetch all the markers from firebase: firestore. the only problem I got is that I can't connect my markers.
maybe at the end of the code I used 'Future' to specify the movement of the camera wile navigating and I used it outside of pageview.builder.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:permission/permission.dart';
class Metro extends StatefulWidget {
#override
_MetroState createState() => _MetroState();
}
String stations;
class _MetroState extends State<Metro> {
// GoogleMapController _controller;
// final CameraPosition _initialPosition = CameraPosition(target: LatLng(9.0131, 38.7240), zoom: 17.0);
LatLng _initialPosition = LatLng(9.0131, 38.7240);
GoogleMapController _controller;
Location _location= Location();
int prevPage;
PageController _pageController;
void _onMapCreated(GoogleMapController _cntrl){
_controller = _cntrl;
_location.onLocationChanged.listen((l) {
_controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(target: LatLng(l.latitude, l.longitude), zoom: 15)));
});
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
void initMarker(specify, specifyId) async {
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
draggable: false,
position:
LatLng(specify['Location'].latitude, specify['Location'].longitude),
infoWindow: InfoWindow(title: specify['Name'], snippet: 'Station'),
);
setState(() {
markers[markerId] = marker;
},
);
_pageController = PageController(initialPage: 0, viewportFraction: 0.8)..addListener(_onScroll);
}
void _onScroll() {
if (_pageController.page.toInt() != prevPage) {
prevPage = _pageController.page.toInt();
moveCamera();
}
}
getMarkerData() async {
Firestore.instance.collection('route 1 markers').getDocuments().then((myMockDoc) {
if (myMockDoc.documents.isNotEmpty) {
for (int i = 0; i < myMockDoc.documents.length; i++) {
initMarker(myMockDoc.documents[i].data, myMockDoc.documents[i].documentID);
}
}
}
);
}
#override
void initState() { enter code here
getMarkerData();
super.initState();
}
#override
Widget build(BuildContext context) {
Set<Marker> getMarker() {
return <Marker>[
Marker(
markerId: MarkerId('Station'),
position: _initialPosition,
icon: BitmapDescriptor.defaultMarker,
infoWindow: InfoWindow(title: 'Home'))
].toSet();
}
return Scaffold(
// floatingActionButton: FloatingActionButton(
// onPressed: (){},
// backgroundColor: Colors.lightGreen,
// child: Icon(Icons.search),
// ),
body: Stack(
children: [
GoogleMap(
markers: Set<Marker>.of(markers.values),
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: _initialPosition, zoom: 25),
onMapCreated: _onMapCreated,
myLocationEnabled: true,
myLocationButtonEnabled: true,
mapToolbarEnabled: false,
),
Positioned(
bottom: 20.0,
child: Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('route 1 markers').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return PageView.builder( // Changes begin here
controller: _pageController,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
final document = snapshot.data.documents[index];
return AnimatedBuilder(
animation: _pageController,
builder: (BuildContext context, Widget widget){
double value = 1;
if (_pageController.position.haveDimensions) {
value = _pageController.page - index;
value = (1 - (value.abs() * 0.3) + 0.06).clamp(0.0, 1.0);
}
return Center(
child: SizedBox(
height: Curves.easeInOut.transform(value) * 125.0,
width: Curves.easeInOut.transform(value) * 350.0,
child: widget,
),
);
},
child: InkWell(
onTap: (){moveCamera();},
child: Stack(
children: [
Center(
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0
),
height: 125,
width: 270,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
offset: Offset(0.0, 4.0),
blurRadius: 10.0,
),
]),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white
),
child: Row(
children: [
Container(
height: 90,
width: 90,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10.0),
topLeft: Radius.circular(10.0)),
image: DecorationImage(
image: NetworkImage(
document['img']),
fit: BoxFit.cover))),
SizedBox(width: 5.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
document['Name'],
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold),
),
Positioned(
bottom: 5.0,
child: Text(
"Addis Ababa, Ethiopia",
style: TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.w600),
),
),
Container(
width: 170,
child: Text(
document['Detail'],
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w300),
),
),
],
)
],
),
),
),
)
],
),
),
);
}
);
}
},
),
))
],
),
);
}
Future<void> moveCamera() async{
_controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
target: document[_pageController.page.toInt()].Location,
zoom: 14.0,
tilt: 45.0,
bearing: 45.0,
)));
}
}
SO I need your help, help me out please. I posted my code
I am building an app called LiveTv which is an app which recommends videos as per varied interests.The code I have written is causing serious lags and as I am proceeding more and more in this app it is becoming next to inoperable.I have included the video of the same in this link https://youtu.be/YQp3E3Lukfk
What I have done is make the call async and I have used a ternary operator wherein which under it loads a circular progress indicator is shown.But it doesn't seems to work only
I have included the code which is the one which is controlled by the bottom navigation bar.The services part of it is not included as its function is only to load the data or the object,but I will include one or two so that you may understand and I dont want to make this question very long
class LiveTvHomePage extends StatefulWidget {
final String title;
LiveTvHomePage({
this.title,
});
#override
_LiveTvHomePageState createState() => _LiveTvHomePageState();
}
class _LiveTvHomePageState extends State<LiveTvHomePage> {
//GlobalKey<ScaffoldState> _drawerKey = GlobalKey<ScaffoldState>();
#override
void initState() {
// TODO: implement initState
super.initState();
handleScroll(); // function which is responsible for updating the isScrollingDown variable whenever the user scrolls down
_services();
setState(() {
_isLoading = false;
});
}
_loadingImage() {
return CircularProgressIndicator();
}
_services() {
Services.loadDataForMovieId().then((movieIdList) {
setState(() {
_homeBannerObjectMovieIdList = movieIdList;
});
});
Services.loadDataForMovieIdofPopularMovieSection().then((movieIdList) {
setState(() {
_popularMoviesMovieId = movieIdList;
});
});
Services.loadDataForPopularTvShowSection().then((homePageSeriesPosterList) {
setState(() {
_seriesData = homePageSeriesPosterList;
});
});
Services.loadDataForMusicSection().then((musicList) {
setState(() {
_musicCategories = musicList;
});
});
Services.loadDataForPlaylistTitle().then((title) {
setState(() {
_musicPlaylistThemeName = title;
});
});
Services.loadDataForPopularNewsChannelsNames().then((nameList) {
setState(() {
_popularNewsChannelNames = nameList;
});
});
Services.loadDataForPopularNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_popularNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsProfilePicUrls().then((urllist) {
setState(() {
_liveNewsChannelProfilePicUrl = urllist;
});
});
Services.loadDataForLiveNewsChannelsNames().then((nameList) {
setState(() {
_liveNewsChannelNames = nameList;
});
});
Services.loadDataForPicOfLatestNews().then((nameList) {
setState(() {
_latestNewsProfilePics = nameList;
});
});
Services.loadDataForOfLatestNewsTitle().then((nameList) {
setState(() {
_latestNewsNewsTitle = nameList;
});
});
Services.loadDataForOfLatestNewsDescription().then((nameList) {
setState(() {
_latestNewsDescription = nameList;
});
});
}
_buildBody(var boxHeight, List<String> youtubeIdUrls) {
return Column(
children: <Widget>[
Stack(
children: <Widget>[
_buildPageView(boxHeight, youtubeIdUrls),
_buildCircleIndicator(youtubeIdUrls),
],
),
],
);
}
_buildPageView(var boxHeight, List<String> youtubeIdUrls) {
return Container(
color: Colors.black87,
height: boxHeight,
child: PageView.builder(
itemCount: 8,
controller: _pageController,
itemBuilder: (BuildContext context, int index) {
try {
// HomeBanner homeBanner=_homeBannelList[index];
return FadeInImage.assetNetwork(
image:
'https://img.youtube.com/vi/${youtubeIdUrls[index].substring(8)}/0.jpg',
placeholder: 'assets/loading.gif',
fit: BoxFit.fill,
);
} catch (e) {
return CircularProgressIndicator();
}
//before return Image.network('https://img.youtube.com/vi/${videoIdOfUrlList[index]}/0.jpg',fit: BoxFit.fill,);
},
onPageChanged: (int index) {
_currentPageNotifier.value = index;
}),
);
}
_buildCircleIndicator(List<String> youtubeIdUrls) {
return Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: CirclePageIndicator(
itemCount: 8,
currentPageNotifier: _currentPageNotifier,
),
),
);
}
Widget imageDisplayed(String picUrl) {
return Row(
children: <Widget>[
const SizedBox(
width: 10,
),
CircleAvatar(
backgroundImage: NetworkImage(picUrl),
radius: MediaQuery.of(context).size.height * 0.08,
backgroundColor: Colors.black,
),
const SizedBox(
width: 10,
),
],
);
}
Widget HorizontalListViewWitCircularCards(
String title, List<String> urlList, List<String> nameList) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.32,
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.07,
color: Colors.black,
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text(
title,
style: TextStyle(fontSize: 16, color: Colors.white),
),
),
),
Container(
height: MediaQuery.of(context).size.height * 0.23,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: _popularNewsChannelNames.length,
itemBuilder: (BuildContext context, int index) => Card(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.symmetric(),
child: Column(
children: <Widget>[
imageDisplayed(urlList[index]),
const SizedBox(
height: 13,
),
Text(
nameList[index],
style: TextStyle(color: Colors.white),
),
],
),
),
),
),
),
],
),
);
}
Widget HorizontalGridViewOfCardsofGradientColor(int count, List<String> lst) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.125 * count,
child: GridView.count(
scrollDirection: Axis.horizontal,
crossAxisCount: count,
shrinkWrap: true,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
children: List.generate(20, (index) {
return Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
borderRadius: BorderRadius.all(Radius.circular(15)),
gradient: LinearGradient(colors: colorsForCardinMusicPage[index]),
),
child: Center(
child: Text(
lst[index],
),
),
);
}),
),
);
}
Widget HorizontalGridViewOfCardsofGradientColorWithtitle(
int count, String title) {
return Column(
);
}
Widget HorizontalListViewOfButtons(List moviesPageButtonNames) {
return Container(
color: Colors.black,
height: MediaQuery.of(context).size.height * 0.13,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: moviesPageButtonNames.length,
itemBuilder: (BuildContext context, int index) => Row(
children: <Widget>[
SizedBox(
width: 7,
),
FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.grey)),
color: Colors.grey[800],
textColor: Colors.white,
onPressed: () {},
child: Text(moviesPageButtonNames[index]),
),
SizedBox(
width: 10,
)
],
),
),
);
}
Widget NewsPageOfBottomNavigator() {
ServicesForNewsPage.loadObjectList().then((newsPageObject) {
_newsPage = newsPageObject;
});
for (var obj in _newsPage.liveChannels) {
_newsPageLiveNewsUrls.add(obj.publisherProfilePic);
_newsPageChannelName.add(obj.publisherName);
}
// print("_newsPageLiveNewsUrls");
// print(_newsPageLiveNewsUrls);
// print("_newsPageLiveNewsNames");
// print(_newsPageChannelName);`
for (var obj in _newsPage.news) {
_newsPagePopularNewsChannelUrls.add(obj.publishers.profilePicUrl);
_newsPagePopularNewsChannelNames.add(obj.publishers.fullName);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWithoutViewAllForLiveNewsChannels(
"Watch Live", _newsPageLiveNewsUrls, _newsPageChannelName),
HorizontalListViewWitCircularCards("Popular News Channel",
_newsPagePopularNewsChannelUrls, _newsPagePopularNewsChannelNames),
VerticalListView(_newsPagePopularNewsChannelNames, true),
],
);
}
Widget LifeStylePageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Lifestyle channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget SportsPageOfBottomNavigator() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
HorizontalListViewWitCircularCards(
"Popular Sports channels", [""], [""]),
VerticalListView(["ssss"], false),
],
);
}
Widget returnToTopButton() {
return Visibility(
visible: _showButton,
child: FlatButton(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 7, 0, 0),
child: Text(
"^",
style: TextStyle(color: Colors.white, fontSize: 27),
),
),
Text(
" Return to top",
style: TextStyle(color: Colors.white),
),
],
),
onPressed: () {
_scrollController.animateTo(0,
duration: Duration(milliseconds: 500), curve: Curves.easeInOut);
},
color: Colors.red,
),
);
}
void showFloationButton() {
setState(() {
_showButton = true;
});
}
void hideFloationButton() {
setState(() {
_showButton = false;
});
}
void handleScroll() async {
// or something else..
_scrollController.addListener(() {
double currentScroll = _scrollController.position.pixels;
double delta = MediaQuery.of(context).size.height;
// print("Current scroll position is ..........$currentScroll");
// print("delta pixel is ..........$delta");
if (currentScroll >= delta) {
showFloationButton();
} else if (currentScroll <= delta) {
hideFloationButton();
}
});
}
#override
void dispose() {
// TODO: implement dispose
_scrollController.removeListener(() {});
super.dispose();
}
#override
Widget build(BuildContext context) {
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
return _isLoading
? _loadingImage()
: Scaffold(
// key: _drawerKey,
appBar: AppBar(
automaticallyImplyLeading: false,
leading: Icon(
Icons.live_tv,
color: Colors.amber,
),
backgroundColor: Colors.black,
title: Text(
widget.title,
style: TextStyle(fontSize: 17, color: Colors.amber),
),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(
MaterialCommunityIcons.xbox_controller_menu,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DrawerWidget()),
);
},
)
],
),
body: SafeArea(
child: SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
),
),
drawer: Drawer(),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.black,
showUnselectedLabels: true,
type: BottomNavigationBarType.shifting,
currentIndex: _selectedIndex,
fixedColor: Colors.amber,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
// Icon(
// FontAwesome.facebook_square,
// color: Colors.amber,
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
MaterialCommunityIcons.video_vintage,
),
title: Text(
'Movies',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.live_tv),
title: Text(
'Tv shows',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.music_video),
title: Text(
'Music',
),
),
// BottomNavigationBarItem(
// backgroundColor: Colors.black,
// icon: Icon(Icons.dehaze),
// title: Text(
// 'More',
// ),
// ),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.radio),
title: Text(
'News',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
FontAwesome.heartbeat,
),
title: Text(
'LifeStyle',
),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(
Ionicons.md_football,
),
title: Text(
'Sports',
),
),
],
),
);
}
}
The services class seems like this in most cases:
class ServicesForNewsPage {
static const String url =
"https://livetvapi.apyhi.com/api/v3/home?pageLocation=News&countries=IN&app_version=13&"
"user_id=44edc2c905ae163f&package_id=livetv.movies.freemovies.watchtv.tvshows&os_platform=android";
static Future<NewsPage> loadObjectList() async {
var res = await http
.get(url, headers: {'Authorization': dartJsonWebTokenGenerator()});
if (res.statusCode == 200) {
// print("response is there for news Page");
final newsPageObjectList = newsPageFromJson(res.body);
return newsPageObjectList;
} else {
print("no response");
return null;
}
}
}
I am quite new to flutter and things are bit hazy as to how to improve the response time.
You're question is quite broad. Have you tried playing with the DevTools?
I don't know the full code of your project, but I think I see that you are initializing all pages every time the build() of your homepage is called.
Consider changing this:
List<Widget> wdgs_option = [
HomePageForBottomNavigator(),
MoviesPageForBottomNavigator(),
TvSHowsPageOfBottomNavigator(),
MusicPageofBottomNavigator(),
// NewsPageOfBottomNavigator(), //dummy for now
NewsPageOfBottomNavigator(),
LifeStylePageOfBottomNavigator(),
SportsPageOfBottomNavigator()
];
to something either 1.:
if (_selectedIndex == 0) {
wdgs_option = HomePageForBottomNavigator();
} else if (hi == _selectedIndex) {
wdgs_option = MoviesPageForBottomNavigator();
} else if (){}
or to 2.:
List<int Function()> wdgs_option = [
() => HomePageForBottomNavigator(),
() => MoviesPageForBottomNavigator(),
() => ...
];
int val = c[1]();
and in that case
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option.elementAt(_selectedIndex),
)
to
SingleChildScrollView(
controller: _scrollController,
child: wdgs_option[_selectedIndex](),
)
I want to put a marker on the map and when I put marker it will get that address and filled into the textbox.
like I've mentioned in this images when I put a marker and then click on show address it will take that address and filled into textboxes. Hope you understand the question. if any query then let me know. I need help please help me. because I am very much stuck in this problem.
Here is some code for google maps.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:tudo/src/styles/colors.dart';
import 'package:tudo/src/utils/navigation_helper.dart';
import 'package:tudo/src/widgets/google_map.dart';
const kGoogleApiKey = "API_KEY";
class BspAddressmapscreen extends StatefulWidget {
BspAddressmapscreen({Key key}) : super(key: key);
#override
_BspAddressmapscreenState createState() => _BspAddressmapscreenState();
}
class _BspAddressmapscreenState extends State<BspAddressmapscreen> {
final homeScaffoldKey = GlobalKey<ScaffoldState>();
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
}
double zoomVal = 5.0;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
NavigationHelper.navigatetoBack(context);
}),
centerTitle: true,
title: Text("Business Address Detail"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('Show Address'),
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BspAddressmapscreen()));
},
),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Stack(
children: <Widget>[
_searchbar(),
_buildGoogleMap(context),
_zoomminusfunction(),
_zoomplusfunction(),
],
),
),
);
}
Widget _zoomminusfunction() {
return Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchMinus, color: Color(0xff008080)),
onPressed: () {
zoomVal--;
_minus(zoomVal);
}),
);
}
Widget _zoomplusfunction() {
return Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(FontAwesomeIcons.searchPlus, color: Color(0xff008080)),
onPressed: () {
zoomVal++;
_plus(zoomVal);
}),
);
}
Future<void> _minus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Future<void> _plus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Widget _buildGoogleMap(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition:
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: 12),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
);
}
Widget _searchbar() {
return Positioned(
top: 50.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0), color: Colors.white),
child: TextField(
decoration: InputDecoration(
hintText: 'Enter Address',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
//onPressed: searchandNavigate,
onPressed: () {},
iconSize: 30.0)),
onChanged: (val) {
setState(() {
// searchAddr = val;
});
},
),
),
);
}
}
Use below code to plot marker and get an address on button click, also use geocoder to get the address from latlng
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
const kGoogleApiKey = "API_KEY";
class BspAddressmapscreen extends StatefulWidget {
BspAddressmapscreen({Key key}) : super(key: key);
#override
_BspAddressmapscreenState createState() => _BspAddressmapscreenState();
}
class _BspAddressmapscreenState extends State<BspAddressmapscreen> {
final homeScaffoldKey = GlobalKey<ScaffoldState>();
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
}
double zoomVal = 5.0;
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
onPressed: () {
/*NavigationHelper.navigatetoBack(context);*/
}),
centerTitle: true,
title: Text("Business Address Detail"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
),
bottomNavigationBar: Container(
color: Colors.transparent,
height: 56,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FlatButton.icon(
icon: Icon(Icons.arrow_back_ios),
label: Text('Show Address'),
textColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {
getUserLocation();
},
),
],
),
),
body: Container(
height: double.infinity,
width: double.infinity,
child: Stack(
children: <Widget>[
_searchbar(),
_buildGoogleMap(context),
_zoomminusfunction(),
_zoomplusfunction(),
],
),
),
);
}
getUserLocation() async {
markers.values.forEach((value) async {
print(value.position);
// From coordinates
final coordinates =
new Coordinates(value.position.latitude, value.position.longitude);
var addresses = await Geocoder.google(kGoogleApiKey)
.findAddressesFromCoordinates(coordinates);
print("Address: ${addresses.first.featureName}");
});
}
Widget _zoomminusfunction() {
return Align(
alignment: Alignment.topLeft,
child: IconButton(
icon: Icon(Icons.remove, color: Color(0xff008080)),
onPressed: () {
zoomVal--;
_minus(zoomVal);
}),
);
}
Widget _zoomplusfunction() {
return Align(
alignment: Alignment.topRight,
child: IconButton(
icon: Icon(Icons.add, color: Color(0xff008080)),
onPressed: () {
zoomVal++;
_plus(zoomVal);
}),
);
}
Future<void> _minus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Future<void> _plus(double zoomVal) async {
final GoogleMapController controller = await _controller.future;
controller.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: zoomVal)));
}
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
Widget _buildGoogleMap(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition:
CameraPosition(target: LatLng(40.712776, -74.005974), zoom: 12),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
markers: Set<Marker>.of(markers.values),
onLongPress: (LatLng latLng) {
// creating a new MARKER
final MarkerId markerId = MarkerId('4544');
final Marker marker = Marker(
markerId: markerId,
position: latLng,
);
setState(() {
markers.clear();
// adding a new marker to map
markers[markerId] = marker;
});
},
),
);
}
Widget _searchbar() {
return Positioned(
top: 50.0,
right: 15.0,
left: 15.0,
child: Container(
height: 50.0,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0), color: Colors.white),
child: TextField(
decoration: InputDecoration(
hintText: 'Enter Address',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 15.0, top: 15.0),
suffixIcon: IconButton(
icon: Icon(Icons.search),
//onPressed: searchandNavigate,
onPressed: () {},
iconSize: 30.0,
),
),
onChanged: (val) {
setState(() {
// searchAddr = val;
});
},
),
),
);
}
}