Can not switch to another page - flutter

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

Related

After Scanning Barcode , how to pass scanned data to a new page?

the thing I will like to ask about is that I want to pass the data in the barcode to a new page after scanning. Is there anyway can I do it?
Hope anyone can solve my problem <3
Had been doing this for my intern for 4 days and I have no clue at all. Hope can solve it as fast as possible
Below is my code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:meditation_app/widgets/category_card.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key key}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String _scanBarcode = 'Unknown';
#override
void initState() {
super.initState();
}
Future<void> scanBarcodeNormal() async {
String barcodeScanRes ;
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes; //Here is the thing I will like to pass to another page
});
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('EzyMerchant'),
actions: <Widget>[
IconButton(
icon: SvgPicture.asset("assets/icons/setting.svg",color: Colors.white,),
onPressed: () {
Navigator.pushNamed(context, '/setting');
},
),
],
),
body: Stack(
children: <Widget>[
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical:20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Good Morning \nAdmin",
style: Theme.of(context)
.textTheme
.headline4
.copyWith(fontWeight: FontWeight.w900),
),
SizedBox(height: 50),
Expanded(
child: Container(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: .85,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
children: <Widget>[
Container(
child: CategoryCard(
title: "Add",
svgSrc: ("assets/icons/Hamburger.svg"),
press: () => scanBarcodeNormal(), //Here is the scan function
),
),
CategoryCard(
title: "Redeem",
svgSrc: "assets/icons/Excrecises.svg",
press: () {},
),
CategoryCard(
title: "Wallet",
svgSrc: "assets/icons/Meditation.svg",
press: () {},
),
CategoryCard(
title: "Voucher",
svgSrc: "assets/icons/yoga.svg",
press: () {},
),
],
),
),
),
],
),
),
)
],
),
);
}
}
You can use arguments property in Navigator.pushNamed like
Navigator.pushNamed(context, '/setting',arguments: _scanBarcode);

i can't see my images on carousel slider before i hot reload

hello everyone i am new in flutter. i have a problem, when i start the application i cant see my images on carousel but when i hot reload i can see them. I think that if i put if/else condition it might work but i could not do it can some one help me about that?
here are the codes;
import 'dart:convert';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:feedme_start/widgets/Navigation_Drawer_Widget.dart';
import 'package:flutter/material.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:http/http.dart';
import 'model/AnaEkran_modeli.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
final imageList = [];
int ct = imageList.length;
class _MyAppState extends State<MyApp> {
String cevap = "";
late Apianaekran _apianaekran;
late Result _result;
get Index => null;
//"getapidata" adlı future methodda apilerle resimleri çekiyorum sonra imageListe ekliyorum
Future<void> getapidata() async {
String url =
"https://www.mobilonsoft.com/fpsapi/default.aspx?op=application_initialization_customer&firmuid=feedmekktc&device_id=web_20210813180900001&device_platform=4&lang=en";
Response responsee = await get(Uri.parse(url));
if (responsee.statusCode == 200) {
//statusCode 200 oldumu bağlantı siteyle doğru şekilde kuruldu demektir.
Map cevapjson =
jsonDecode(responsee.body); //cevap, json code daki body i alır.
Apianaekran ekran = Apianaekran.fromJson(cevapjson);
ct = ekran.result.sliderImages.length;
print(ct);
int i = 0;
while (i < ct) {
imageList.add(ekran.result.sliderImages[i].imageUrl);
print(ekran.result.sliderImages[i].imageUrl);
i++;
}
} else {
print("bir sorun oluştu");
}
print("resimler başarıyla çekildi");
print(imageList.length);
}
#override
void initState() {
getapidata();
}
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.red,
title: Center(child: Text("FEED ME")),
actions: <Widget>[
IconButton(onPressed: () {}, icon: Icon(Icons.call))
],
),
drawer: NavigationDrawerWidget(),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Column(
children: [
Container(
constraints: BoxConstraints.expand(height: 200),
child: CarouselSlider(
options: CarouselOptions(
enlargeCenterPage: true,
enableInfiniteScroll: true,
autoPlay: true),
items: imageList
.map((e) => ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.network(
e,
width: 1050,
height: 350,
fit: BoxFit.cover,
)
],
),
))
.toList())), //imageSlider(context),),
/* Divider(,,
color: Colors.red,
),*/
SizedBox(
height: 75,
),
ElevatedButton.icon(
onPressed: () {
getapidata();
}, //api çekiminin denemesini bu tuşnan yaparım şimdilik
icon: Icon(Icons.add),
label: Text("Yeni Sipariş Ver"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.red)),
),
SizedBox(
height: 50,
),
// Text(_anaEkranJsonlar.statusCodeDescription),
SizedBox(
height: 150,
),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.add),
label: Text("Canlı Destek"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
SizedBox(
width: 5,
),
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.sms),
label: Text("Fırsatlar"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
],
),
SizedBox(
height: 30,
),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.exit_to_app),
label: Text("Giriş"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
SizedBox(
width: 5,
),
Expanded(
child: ElevatedButton.icon(
onPressed: () {},
icon: Icon(Icons.person_add),
label: Text("Kayıt Ol"),
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[900])),
),
),
],
)
],
),
)
/*Swiper(itemCount: imageList.length,
itemBuilder: (context, index) {
return Image.network(imageList[index],/*errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace), {return const("resim yüklenemedi")},*/
fit: BoxFit.cover,);
},)*/
),
);
}
}
this is the picture of first start
this one is after i hot reload the code
it has to be like in 2nd pic. can someone help me ?
You need to update the state of your widget inside getapidata after you've loaded all the images:
Future<void> getapidata() async {
String url = "https://www.mobilonsoft.com/fpsapi/default.aspx?op=application_initialization_customer&firmuid=feedmekktc&device_id=web_20210813180900001&device_platform=4&lang=en";
Response responsee = await get(Uri.parse(url));
if (responsee.statusCode == 200) {
// ...
setState(() {});
}
}
The above will already work as expected, but you should consider using a FutureBuilder. Also, you should put
final imageList = [];
int ct = imageList.length;
inside your widget's state, and not in the global scope.

Getting Error while Home widget (MyHomepage) loading

I am getting The following error while Run my app default page (Homepage) .
════════ Exception caught by widgets library ═══════════
The following ArgumentError was thrown building MyHomePage(dirty, dependencies: [MediaQuery, _EffectiveTickerMode], state: _MyHomePageState#7da5f(ticker inactive)):
Invalid argument(s)
**The Tracker showing the following reasons:**
The relevant error-causing widget was:
MyHomePage file:///F:/Orangebd/app/GoogleDriveClone-Flutter/lib/Screen/Home.dart:37:15
When the exception was thrown, this was the stack:
#0 _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1 _MyHomePageState.build (package:googledriveclone_flutter/Screen/Home.dart:133:45)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4716:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4772:11)
...
══════════════════════════════════════════
During that error, the screen appears something like that
Here is my Home page code
import 'package:fab_circular_menu/fab_circular_menu.dart';
//import 'package:file_picker/file_picker.dart';
import 'package:floating_action_bubble/floating_action_bubble.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:googledriveclone_flutter/Screen/Files.dart';
import 'package:googledriveclone_flutter/Screen/HomeScreen.dart';
import 'package:googledriveclone_flutter/Screen/LoginPage.dart';
import 'package:googledriveclone_flutter/Screen/Profile.dart';
import 'package:googledriveclone_flutter/Widget/constants.dart';
import 'package:prompt_dialog/prompt_dialog.dart';
import 'package:sk_alert_dialog/sk_alert_dialog.dart';
import 'package:storage_capacity/storage_capacity.dart';
import 'IssudFile.dart';
void main() {
runApp(HomePage());
}
class HomePage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
try {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Digilocker',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Digilocker'),
);
}
catch(e){
print('Loading expception of page'+e.toString());
}
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
Widget _widgetBody = HomeScreen();
int _currrentIndex = 0;
Animation<double> _animation;
AnimationController _animationController;
TextEditingController _foldername = TextEditingController();
String _fileName;
var scaffoldKey = GlobalKey<ScaffoldState>();
bool isFolder;
double _diskSpace = 0;
var _freespace ;
var _freespacemb;
var _occupiedSpace ;
var _totalSpace;
#override
void initState() {
// TODO: implement initState
// _controller.addListener(() => _extension = _controller.text);
_getStorgeInfo();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 300),
);
final curvedAnimation = CurvedAnimation(curve: Curves.easeInOut, parent: _animationController);
_animation = Tween<double>(begin: 0, end: 1).animate(curvedAnimation);
// initDiskSpace();
super.initState();
}
#override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onItemTapped(int index) async{
setState(() {
if(index == 0){
_currrentIndex = index;
_widgetBody = HomeScreen();
}
else if(index == 1){
_currrentIndex = index;
_widgetBody = MyIssuedDocScreen();
}
else if(index == 2){
_currrentIndex = index;
_widgetBody = Center(child: Text('Shared documents'),);
}
else if(index == 3){
_currrentIndex = index;
_widgetBody = MyDriveScreen();
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
endDrawerEnableOpenDragGesture: false, // This way it will not open
// endDrawer: Drawer(),
drawer: new Drawer(
elevation: 10,
child: new ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
DrawerHeader(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset('assets/digi_locker.png', width: MediaQuery.of(context).size.width*0.30,),
SizedBox(height: 10,),
Text('Available space: '+_freespace+'\t (MB)'),
]
),
decoration: BoxDecoration(
color: kPrimaryLightColor,
),
),
ListTile(
leading: Icon(Icons.person),
title: Text('My profile'),
onTap: () {
// Get.back();
Get.to(profilePage());
},
),
Divider(),
ListTile(
leading: Icon(Icons.create_new_folder),
title: Text('Create folder'),
onTap: () {
// Get.back();
_showMyDialog();
},
),
ListTile(
leading: Icon(Icons.cloud_upload_rounded),
title: Text('File upload'),
onTap: () {
// Get.back();
},
),
ListTile(
leading: Icon(Icons.six_ft_apart_outlined),
title: Text('Issued documents'),
onTap: () {
// Get.back();
},
),
Divider(),
ListTile(
leading: Icon(Icons.translate_rounded),
title: Text('Change lagnuage'),
onTap: () {
// Get.back();
//Get.offAll(LoginPage());
//Do some stuff here
//Closing programmatically - very less practical use
scaffoldKey.currentState.openEndDrawer();
},
),
ListTile(
leading: Icon(Icons.logout),
title: Text('Logout'),
onTap: () {
// Get.back();
Get.offAll(LoginPage());
//Do some stuff here
//Closing programmatically - very less practical use
scaffoldKey.currentState.openEndDrawer();
},
)
],
),
),
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
brightness: Theme.of(context).brightness,
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children:
[
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(35)),
color: Colors.grey.shade50,
),
child: TextFormField(
decoration: InputDecoration(
hintText: "Search in locker",
border: InputBorder.none,
icon: Container(
margin: EdgeInsets.only(left: 10),
child: Icon(Icons.search, color: kPrimaryColor,)
),
),
),
),
),
]
),
iconTheme: IconThemeData(color: kPrimaryColor),
actions: <Widget>[
IconButton(
onPressed: (){
print("Sync started");
showSnackMessage(context,"Sync Started please wait...", scaffoldKey,'');
},
icon: Icon(
Icons.sync,
color:kPrimaryColor,
),
),
IconButton(
icon: Container(
height: 50,
width: 50,
margin: EdgeInsets.all(5),
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.white,
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage("https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
),
),
onPressed: () {
// do something
},
)
],
),
body: SafeArea(
child: Container(
padding: EdgeInsets.all(15.0),
child: _widgetBody
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
//Init Floating Action Bubble
floatingActionButton: FloatingActionBubble(
// Menu items
items: <Bubble>[
// Floating action menu item
Bubble(
title:"Upload",
iconColor :kPrimaryColor,
bubbleColor : Colors.white.withOpacity(0.9),
titleStyle:TextStyle(fontSize: 16 , color: kPrimaryColor),
icon:Icons.cloud_upload,
onPress: () {
// OpenFilePicker();
_animationController.reverse();
_openFileType(context);
},
),
// Floating action menu item
Bubble(
title:"Folder",
icon:Icons.create_new_folder,
iconColor :kPrimaryColor,
bubbleColor : Colors.white.withOpacity(0.9),
titleStyle:TextStyle(fontSize: 16 , color: kPrimaryColor),
onPress: () {
_animationController.reverse();
print('creating folder');
_showMyDialog();
},
),
//Floating action menu item
],
// animation controller
animation: _animation,
// On pressed change animation state
onPress: _animationController.isCompleted
? _animationController.reverse
: _animationController.forward,
// Floating Action button Icon color
iconColor: kPrimaryColor,
// Flaoting Action button Icon
icon: AnimatedIcons.menu_close,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currrentIndex,
type: BottomNavigationBarType.fixed,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedItemColor: kPrimaryColor,
onTap: _onItemTapped,
items: [
BottomNavigationBarItem(
icon: _currrentIndex==0?Icon(Icons.home,size: 25,):Icon(Icons.home_outlined,size: 25),
title: Text("Home")
),
BottomNavigationBarItem(
icon: _currrentIndex==1?Icon(Icons.file_download_done,size: 25,):Icon(Icons.file_download_done_outlined,size: 25),
title: Text("Issued")
),
BottomNavigationBarItem(
icon: _currrentIndex==2?Icon(Icons.supervised_user_circle,size: 25,):Icon(Icons.supervised_user_circle,size: 25),
title: Text("Shared")
),
BottomNavigationBarItem(
icon: _currrentIndex==3?Icon(Icons.folder,size: 25,):Icon(Icons.folder_open,size: 25),
title: Text("My locker")
),
],
), );
}
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Colors.white,
elevation: 13,
title: Text('Create folder'),
content: TextField(
onChanged: (value) { },
controller: _foldername,
decoration: InputDecoration(hintText: "your folder/directory name",
suffixIcon: IconButton(
onPressed: () => _foldername.clear(),
icon: Icon(Icons.clear),
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cancel', style: TextStyle(color: Colors.red),),
onPressed: () {
//Navigator.pop(_);
Navigator.of(context).pop();
// _animationController.reverse();
},
),
TextButton(
child: Text('Create', style: TextStyle(color: kPrimaryColor),),
onPressed: () {
createFolder(context, scaffoldKey, _foldername.text.toString()) ;
Get.back();
//Navigator.of(context).pop();
// _animationController.reverse();
},
),
],
);
},
);
}
void _openFileType(BuildContext context) {
SKAlertDialog.show(
context: context,
type: SKAlertType.radiobutton,
radioButtonAry: {'Certificate': 1, 'Signature': 2, 'NID': 3, 'Passport': 4, 'Driving licence': 5},
title: 'Choose File category',
onCancelBtnTap: (value) {
print('Cancel Button Tapped');
Navigator.of(context).pop(false);
},
onRadioButtonSelection: (value) {
print('onRadioButtonSelection $value');
},
);
}
/* Future<void> initDiskSpace() async {
double diskSpace = 0;
diskSpace = await DiskSpace.getFreeDiskSpace;
if (!mounted) return;
setState(() {
_diskSpace = diskSpace;
});
}
*/
Future<void> _getStorgeInfo() async{
_freespace = await StorageCapacity.getFreeSpace;
//_freespacemb = await StorageCapacity.toMegaBytes(double.parse(_freespace.toString()));
_occupiedSpace = await StorageCapacity.getOccupiedSpace;
_totalSpace = await StorageCapacity.getTotalSpace;
}
}
NOTE: if I Hot Reload this page, it's working okay again
Please help.
the problem is, you are getting your data in the initState method, but your widget's build is being completed before initializing the data to _freespace, and that's why the error is appearing.
as a solution, I suggest removing _getStorgeInfo() call from initState, and implementing the following structure:
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
endDrawerEnableOpenDragGesture: false, // This way it will not open
// endDrawer: Drawer(),
drawer: new Drawer(
...
),
appBar: AppBar(
...
),
body: SafeArea(
child: Container(
padding: EdgeInsets.all(15.0),
child: FutureBuilder(
future: _getStorgeInfo(),
builder: (context, snapshot) {
if(snapshot.connectionState!=ConnectionState.Done) return CircularProgressIndicator();
return _widgetBody;
},
),
),
));
}

Flutter how can i add custom image marker on google map

I am suing Flutter plugin to show map in my app which is done issue is I have fixed long and latitude value and I need to show a custom image marker on that values. Its showing a simple red marker now but don't know how to show the image icon.
class _MapScreenState extends State<MapScreen> {
Completer<GoogleMapController> _controller = Completer();
#override
void initState() {
super.initState();
_onMapCreated();
}
final currentPostion = LatLng(24.916404, 67.130654);
final Map<String, Marker> _markers = {};
_onMapCreated() {
setState(() {
_markers.clear();
final marker = Marker(
markerId: MarkerId('asda'),
position: LatLng(24.916404, 67.130654),
infoWindow: InfoWindow(
title: 'dsaa',
snippet: 'sss',
),
);
_markers['saa'] = marker;
}
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
leading: GestureDetector(
onTap:(){
Navigator.pop(context);
},child: Icon(Icons.arrow_back)),
centerTitle: true,
flexibleSpace: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/nav.jpg'),
fit: BoxFit.cover,
),
),
),
backgroundColor: Colors.transparent,
title: Text('My Location', style: TextStyle(fontFamily: 'UbuntuBold'),),
actions: [
Padding(
padding: const EdgeInsets.only(right: 15),
child: Icon(
Icons.notifications_none,
size: 33,
),
)
]),
body: GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: currentPostion,
zoom: 20,
),
markers: _markers.values.toSet(),
),
);
}
you can see i have added marker in code butnot able to change it to image.
GoogleMap widget contains property markers which is a Set<Marker>.
https://medium.com/#zeh.henrique92/google-maps-flutter-marker-circle-and-polygon-c71f4ea64498

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
{
.....
...
..
}