I am using a package permission handler in my app. I am using an android 9 mobile.
This is my AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.light_chat">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION"/>
<application
android:requestLegacyExternalStorage="true">
android:label="light_chat"
android:name="${applicationName}"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges=
"orientation|keyboardHidden|keyboard|screenSize|
smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
android:usesCleartextTraffic="true"
</application>
</manifest>
And This is my homePage where I am making the permission function
and calling in initState();
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:light_chat/layout/const_size.dart';
import 'package:light_chat/layout/repeateCode.dart';
import 'package:permission_handler/permission_handler.dart';
import 'sign_in.dart';
import 'functions.dart';
import 'chat_room.dart';
import 'package:permission_handler/permission_handler.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
late final size = MediaQuery
.of(context)
.size;
bool isLoading = false;
Map<String, dynamic>? userMap;
TextEditingController _serachBarController = TextEditingController();
FirebaseAuth _auth = FirebaseAuth.instance;
String chatRoomId(String user1, String user2){
if(user1[0].toLowerCase().codeUnits[0] >
user2[0].toLowerCase().codeUnits[0]){
return '$user1 $user2';
}
else
{
return '$user2 $user1';
}
}
#override
void onSearch() async {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
setState(() {
isLoading = true;
});
await _firestore.collection('users').where(
'email', isEqualTo: _serachBarController.text)
.get().then((value) {
setState(() {
if (value.docs.length > 0) {
userMap = value.docs[0].data();
print(userMap);
isLoading = false;
}
});
});
}
FirebaseFirestore _firestore = FirebaseFirestore.instance;
#override
void initState() {
permission();
WidgetsBinding.instance.addObserver(this);
statusChange('Online');
// TODO: implement initState
super.initState();
}
Here is the permission function i want to allow my mobile second permission
var status1
but my stack thorwing exception that is no permission in menifest file.
i am using android 9 so this is the problem
those permissions i am adding in menifest, for android 11.
i want to know which permission i add in menifest for android 9 or under 9.
void permission ()async{
// var status0= await Permission.storage.status;
// if (!status0.isGranted){
// await Permission.storage.request();
// }
var status1= await Permission.manageExternalStorage.status;
if (!status1.isGranted){
await Permission.manageExternalStorage.request();
}
}
void statusChange(String status)async{
await _firestore.collection('users').doc(_auth.currentUser!.uid).update(
{
'status' : status
});
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
if(state == AppLifecycleState.resumed){
statusChange('Online');
}
else
{
statusChange('Offline');
}
// TODO: implement didChangeAppLifecycleState
super.didChangeAppLifecycleState(state);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home',),
actions: [
IconButton(onPressed: () => logOut(context), icon: Icon(Icons.logout))
],
backgroundColor: Colors.blue,),
body: isLoading ?
Center(child:
Container(
height: size.height / 20,
width: size.width / 20,
child: CircularProgressIndicator(),
),)
: Column(
children: [
SizedBox(height: 10.0,),
RepeateTextFieldCode(controller: _serachBarController,
keyboardType: TextInputType.emailAddress,
lableText: 'Search'),
ElevatedButton(onPressed: () => onSearch(),
child: Text('Search', style: buttonText,),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
),
userMap != null ?
ListTile(
onTap: () {
String roomId = chatRoomId(_auth.currentUser!.displayName!,
userMap?['name']);
Navigator.push(context,MaterialPageRoute(builder: (_)=> ChatRoom(
chatRoomId: roomId,
userMap: userMap,
)));
},
title: Text(userMap?['name'], style: titleText,),
subtitle: Text(userMap?['email'], style: subtitleText,),
leading: Icon(Icons.account_box, color: Colors.black,),
trailing: Icon(Icons.chat, color: Colors.black,),
) :
Container(),
],
),
);
}
}
Related
I use Flutter Image Crop, Image editing working but doesnt show image. I press the button. I choose the picture. I'm arranging. Then I hit the 'check' button. However, the picture does not appear on the screen.I don't know what to do. I've been working on it for 2 days but I couldn't find the error.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(cropBen1());
}
class cropBen1 extends StatelessWidget {
const cropBen1({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Image Cropper Ben",
home: cropBen2(),
);
}
}
class cropBen2 extends StatefulWidget {
const cropBen2({Key? key}) : super(key: key);
#override
State<cropBen2> createState() => _cropBen2State();
}
class _cropBen2State extends State<cropBen2> {
File? _image,imageFile;
Future getImage(ImageSource source) async{
try {
final image=await ImagePicker().pickImage(source: source);
if(image==null) return;
final imageTemporary = File(image.path);
this._image=imageTemporary;
_cropImage(image?.path);
} on PlatformException catch (e) {
print('Failed to pick image : $e');
}
}
_cropImage(filePath) async {
final croppedImage = await ImageCropper().cropImage(sourcePath: filePath,maxHeight: 1080,maxWidth: 1080);
if (croppedImage != null) {
imageFile = croppedImage as File?;
setState(() {});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(centerTitle:true,title: Text("Image Cropper Ben"),),
body: Center(child: Column(children: [
SizedBox(height: 30,),
Container(child: imageFile != null ? Image.file(imageFile!,width: 300,height: 300,fit: BoxFit.cover,)
: Image.network('http://gezilecekyerler.com/wp-content/uploads/2017/03/van.jpg'),),
SizedBox(height: 20,),
ElevatedButton(
onPressed: ()=>{getImage(ImageSource.gallery)},
child: Container(
width: 250,
height: 50,
child: Row(children: [
Icon(Icons.image_outlined),
SizedBox(width: 20,),
Text("Resim Yükle",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 24),),
],),
)),
],),),
);
}
}
AndroidManifest.XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deneme_flutter">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="deneme_flutter"
android:name="${applicationName}"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"/>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
I'm trying to create nfc emulator in flutter app using the dart package (https://pub.dev/packages/nfc_emulator)
I have added emulator services to AndroidManifest.xml file and then started getting build error.
This is the emulator service tag of AndroidManifest.xml.
<service
android:name="io.flutter.plugins.nfc_emulator.NfcEmulatorService"
android:exported="true"
android:permission="android.permission.BIND_NFC_SERVICE">
<!-- Intent filter indicating that we support card emulation. -->
<intent-filter>
<action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!--
Required XML configuration file, listing the AIDs that we are emulating cards
for. This defines what protocols our card emulation service supports.
-->
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="#xml/aid_list" />
</service>
This is my dart code:
class NFC extends StatefulWidget {
#override
State<NFC> createState() => _NFCState();
}
class _NFCState extends State<NFC> {
// BottomSheetWidget({super.key});
TextEditingController controller = TextEditingController();
TextEditingController ctrl = TextEditingController();
String _platformVersion = 'Unknown';
NfcStatus _nfcStatus = NfcStatus.unknown;
bool _started = false;
#override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
String? platformVersion;
NfcStatus nfcStatus = NfcStatus.unknown;
try {
platformVersion = await NfcEmulator.platformVersion;
nfcStatus = await NfcEmulator.nfcStatus;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion ?? 'Unknown';
_nfcStatus = nfcStatus;
});
}
#override
Widget build(BuildContext context) {
return Container(
height: 800,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
// mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 8),
child: Text('Add details'),
),
TextField(controller: controller, hint: 'cardAid'),
TextField(
controller: ctrl,
hint: 'cardUid',
),
TextButton(
onPressed: () {
startStopEmulator();
},
child: Text('Submit'))
],
),
),
);
}
void startStopEmulator() async {
if (_started) {
await NfcEmulator.stopNfcEmulator();
} else {
await NfcEmulator.startNfcEmulator(
controller.text,
ctrl.text,
);
//}
}
}
This is the build error that I'm getting.
Exception: Gradle task assembleDebug failed with exit code 1
I started getting error on adding the emulator services.
Notification click time FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { } not calling . how to solve this issue anyone help me .
FCM response :
{load_id: 1045, type: load_created_by_client, title: New load created, click_action: FLUTTER_NOTIFICATION_CLICK, message: New load #1045 created., added_on: 2022-06-11 08:56:16}
Manifest file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xxx.xxx.xxx">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<application
android:label="etruxx"
android:usesCleartextTraffic="true"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:exported="true"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- <meta-data-->
<!-- android:name="firebase_messaging_auto_init_enabled"-->
<!-- android:value="false" />-->
<!-- <meta-data-->
<!-- android:name="firebase_analytics_collection_enabled"-->
<!-- android:value="false" />-->
<!-- <meta-data-->
<!-- android:name="firebase_analytics_collection_deactivated"-->
<!-- android:value="false" />-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
</application>
</manifest>
Main.dart file code here
import 'dart:async';
import 'package:xxxx/home/dispatch_home.dart';
import 'package:xxxx/size_config.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'Dashboard.dart';
import 'home/load_view_dispatch.dart';
/// To verify things are working, check out the native platform logs.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
print(message.data.toString());
RemoteNotification? notification = message.notification;
// print(message.notification.toString());
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
AndroidNotification? android = message.notification?.android;
print(notification);
print(android);
print(!kIsWeb);
// if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'456546545675', // id
'High 45654654 Notifications', // title
//'This channel is used for important notifications.', // description
importance: Importance.high, playSound: true
);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
print('A new onMessageOpenedApp event was published! : '+loadid);
});
flutterLocalNotificationsPlugin.show(
int. parse(dataval['load_id']),
dataval['title'],
dataval['message'],
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
//channel.description,
// TODO add a proper drawable resource to android, for now using
// one that already exists in example app.
playSound: true,
priority: Priority.high,
importance: Importance.high,
icon: "#mipmap/ic_launcher",
),
),
);
}else{
print('go to else');
}
}
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;
/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
//'This channel is used for important notifications.', // description
importance: Importance.high, playSound: true
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
// SizeConfig().init(context);
return MaterialApp(
title: 'Etruux',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Welcome Etruux'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void initState() {
super.initState();
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage? message) {
if (message != null) {
print("calling initial");
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => load_view_dispatch(loadid)));
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print(message.data.toString());
RemoteNotification? notification = message.notification;
// print(message.notification.toString());
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
AndroidNotification? android = message.notification?.android;
print(notification);
print(android);
print(!kIsWeb);
// if (notification != null && android != null && !kIsWeb) {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
print('A new onMessageOpenedApp event was published!');
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => load_view_dispatch(loadid)));
});
if (!kIsWeb) {
flutterLocalNotificationsPlugin.show(
int. parse(dataval['load_id']),
dataval['title'],
dataval['message'],
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
//channel.description,
// TODO add a proper drawable resource to android, for now using
// one that already exists in example app.
playSound: true,
priority: Priority.high,
importance: Importance.high,
icon: "#mipmap/ic_launcher",
),
),
);
}else{
print('go to else');
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
Map<String, dynamic> dataval=message.data;
print(dataval['load_id']);
String loadid=dataval['load_id'];
print('A new onMessageOpenedApp event was published!');
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => load_view_dispatch(loadid)));
});
getToken();
Timer(Duration(seconds: 5),
()=>Navigator.pushReplacement(context,
MaterialPageRoute(builder:
(context) =>
Dashboard()
)
)
);
}
#override
void didChangeAppLifecycleState(final AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
setState(() {
// ...your code goes here...
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// RemoteNotification? notification = message.notification;
// AndroidNotification? android = message.notification?.android;
print("fail");
Map<String, dynamic> dataval=message.data;
print(dataval['type']);
if(dataval['type'].compareTo("load_created_by_client")==0) {
print("success");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => dispatch_home()
),
);
}
});
});
}
}
late String token;
getToken() async {
token = (await FirebaseMessaging.instance.getToken())!;
print(token);
}
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
appBar: AppBar(
title: Text("testttt"),
),
body: Stack(
fit: StackFit.expand,
children: <Widget>[
// Container(
// decoration: BoxDecoration(color: Colors.deepPurple),
// ),
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 4,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// FlutterLogo(
// size: 100.0,
// ),
Image.asset('assets/testicon.png', height: 170,
width: 250,),
Padding(
padding: EdgeInsets.only(top: 10.0),
),
],
),
),
),
],
)
],
),
);
}
}
pubspec.file
firebase_core: ^1.17.1
firebase_messaging: ^11.4.1
flutter_local_notifications: ^9.5.3+1
firebase_analytics: ^9.1.9
fluttertoast: ^8.0.9
cloud_firestore: ^3.1.17
overlay_support: ^2.0.0
firebase_auth: ^3.3.19
App closed or open scenario notification working and also values print but notification click time that related functionality not calling. inside print value also not working. anyone help. how to solve this issue. any mistake here
I'm using the geolocator plugin to access the user's location but it seems like it does not work, cause when I run my code I get the error on message.
I have done all the geolocation configuration, but I have the problem.
Adding the Geolocator plugin(pubspec.yaml)
dependencies:
flutter:
sdk: flutter
geolocator: ^5.1.3
For android, head on over to your AndroidManifest.xml and add either of these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Source code for getting address
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}
The problem I get when I run my code is here.
Try flutter clean on terminal and then run the app again, You can also use location plugin instead of Geolocator, to get the user's location
Here I am working with one project where I need to click an image from the camera and preview it in another screen. so I've done it. but there is some issue here I need to click square image and display also the square image I've tried lots of solutions but it won't work. hope you understand the question. please help me. your little help can make my day.
Here is my code.
availableCameras().then((availableCameras) {
cameras = availableCameras;
if (cameras.length > 0) {
setState(() {
selectedCameraIdx = 0;
});
_initCameraController(cameras[selectedCameraIdx]).then((void v) {});
} else {
print("No camera available");
}
}).catchError((err) {
print('Error: $err.code\nError Message: $err.message');
});
//---------------------------------------------------------------------
AspectRatio(
aspectRatio: 1,
child: ClipRect(
child: Transform.scale(
scale: 1 / controller.value.aspectRatio,
child: Center(
child: AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller),
),
),
),
),
)
This is for Display image
Image.file(
File(widget.imagePath),
)
I hope , This is the suitable answer as you wanted.
Plugins: camera, image_cropper
Run this code:
import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
Future<void> main() async {
// Ensure that plugin services are initialized so that `availableCameras()`
// can be called before `runApp()`
WidgetsFlutterBinding.ensureInitialized();
// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();
// Get a specific camera from the list of available cameras.
final firstCamera = cameras.first;
runApp(
MyApp(firstCamera: firstCamera,)
);
}
class MyApp extends StatelessWidget {
final firstCamera;
// This widget is the root of your application.
MyApp({this.firstCamera});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
// routes: routes,
home: TakePictureScreen(
// Pass the appropriate camera to the TakePictureScreen widget.
camera: firstCamera,
),
);
}
}
// A screen that allows users to take a picture using a given camera.
class TakePictureScreen extends StatefulWidget {
final CameraDescription camera;
const TakePictureScreen({
Key key,
#required this.camera,
}) : super(key: key);
#override
TakePictureScreenState createState() => TakePictureScreenState();
}
class TakePictureScreenState extends State<TakePictureScreen> {
CameraController _controller;
Future<void> _initializeControllerFuture;
#override
void initState() {
super.initState();
// To display the current output from the Camera,
// create a CameraController.
_controller = CameraController(
// Get a specific camera from the list of available cameras.
widget.camera,
// Define the resolution to use.
ResolutionPreset.medium,
);
// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
}
#override
void dispose() {
// Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(title: Text('Take a picture')),
// Wait until the controller is initialized before displaying the
// camera preview. Use a FutureBuilder to display a loading spinner
// until the controller has finished initializing.
body: Center(
child: Container(
width: size,
height: size,
child: ClipRect(
child: OverflowBox(
alignment: Alignment.center,
child: FittedBox(
fit: BoxFit.fitWidth,
child: Container(
width: size,
height:size,
child:FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the Future is complete, display the preview.
return CameraPreview(_controller);
} else {
// Otherwise, display a loading indicator.
return Center(child: CircularProgressIndicator());
}
},
),
),
),
),
),
)
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera_alt),
// Provide an onPressed callback.
onPressed: () async {
// Take the Picture in a try / catch block. If anything goes wrong,
// catch the error.
try {
await _controller.takePicture().then((value) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayPictureScreen(imagePath: value.path),
),
);
});
} catch (e) {
// If an error occurs, log the error to the console.
print(e);
}
},
),
);
}
}
// A widget that displays the picture taken by the user.
class DisplayPictureScreen extends StatefulWidget {
final String imagePath;
const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);
#override
_DisplayPictureScreenState createState() => _DisplayPictureScreenState();
}
class _DisplayPictureScreenState extends State<DisplayPictureScreen> {
var finalImage ;
#override
void initState() {
super.initState();
croppingImage();
}
croppingImage()async{
File croppedFile = await ImageCropper.cropImage(
sourcePath: File(widget.imagePath).path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.pink,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
minimumAspectRatio: 1.0,
)
);
if(croppedFile!=null){
setState(() {
finalImage = croppedFile;
});
}else{
setState(() {
finalImage = File(widget.imagePath);
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Display the Picture')),
// The image is stored as a file on the device. Use the `Image.file`
// constructor with the given path to display the image.
body: Center(
child:
finalImage !=null ?
Container(
height: MediaQuery.of(context).size.height/2, //400
// width: MediaQuery.of(context).size.width/1.2,//400
decoration: BoxDecoration(
border: Border.all(color: Colors.red),
image: DecorationImage(
image: FileImage(finalImage),
fit: BoxFit.cover
)
),
)
:Container()
)
);
}
}
Modify with your AndroidManifest.xml with this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="myapp"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-Add Crop Activity -->
<!-Add this line -->
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"/>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Camera View in Square shape:
Cropping captured image before showing:
Captured image in Square view:
You should use image cropper for this feature. when you take image from camera or gallery just crop image through this : https://pub.dev/packages/image_cropper