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>
Related
The problem I'm facing is related to my Flutter mobile app that uses ARCore. On the second page of the app, I've implemented an AR view that displays augmented reality content. However, whenever I press the back button to navigate back to the previous page, the app becomes unresponsive. I'm looking for suggestions and advice on how to resolve this issue.
my first page code named "home_page.dart"
import 'package:flutter/material.dart';
import 'package:flutter_ar_project/ar_page.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context)
{
return const HelloWorld();
}
)
);
},
child: const Text("Click this to go ar"),
),
);
}
}
the 2nd page dart code named "ar_page.dart"
import 'package:arcore_flutter_plugin/arcore_flutter_plugin.dart';
import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart' as vector;
class HelloWorld extends StatefulWidget {
const HelloWorld({Key? key}) : super(key: key);
#override
HelloWorldState createState() => HelloWorldState();
}
class HelloWorldState extends State<HelloWorld> {
late ArCoreController? arCoreController;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("AR"),
),
//body: Text("something"),
body: ArCoreView(onArCoreViewCreated: _onArCoreViewCreated),
);
}
void _onArCoreViewCreated(ArCoreController controller) {
arCoreController = controller;
//_addSphere(arCoreController);
}
void _addSphere(ArCoreController controller) {
final material = ArCoreMaterial(color: const Color.fromARGB(120, 66, 134, 244));
final sphere = ArCoreSphere(
materials: [material],
radius: 0.1,
);
final node = ArCoreNode(
shape: sphere,
position: vector.Vector3(0, 0, -1.5),
);
controller.addArCoreNode(node);
}
#override
void dispose() {
super.dispose();
arCoreController?.dispose();
}
}
the error i got after i press the back button to go the previous page
E/native (18299): E0000 00:00:1676487723.958837 18299 normal_detector_cpu.cc:233] Error graph_->WaitUntilIdle():INTERNAL: RET_CHECK failure (third_party/mediapipe/framework/scheduler.cc:278) state_ != STATE_NOT_STARTED (0 vs. 0)
Error from the debugger
i tried to change the dispose() method in the ar_page.dart HellowWordState class to
#override
void dispose() {
super.dispose();
if (arCoreController != null) {
arCoreController?.dispose();
}
}
and i still got the similar error as above i really dont know how to solve it
here my my android build.gradle file
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
//throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 33
//compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
//sourceCompatibility 1.8
//targetCompatibility 1.8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.flutter_ar_project"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
//minSdkVersion flutter.minSdkVersion
minSdkVersion 24
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.ar:core:1.33.0'
// Provides ArFragment, and other UX resources.
implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.8.0'
// Alternatively, use ArSceneView without the UX dependency.
implementation 'com.google.ar.sceneform:core:1.8.0'
}
here is my AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutter_ar_project">
<uses-sdk android:minSdkVersion = "24"/>
<uses-permission android:name="android.permission.CAMERA" />
<!-- Limits app visibility in the Google Play Store to ARCore supported devices
(https://developers.google.com/ar/devices). -->
<uses-feature android:name="android.hardware.camera.ar" />
<application
android:label="flutter_ar_project"
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"
/>
<meta-data android:name="com.google.ar.core" android:value="required" />
<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" />
</application>
</manifest>
and pubspec.yaml dependencies
dependencies:
ar_flutter_plugin: ^0.7.3
arcore_flutter_plugin: ^0.1.0
camera: null
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
path: null
path_provider: null
dev_dependencies:
flutter_lints: ^2.0.0
flutter_test:
sdk: flutter
forget to mention here my main.dart file
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_ar_project/design_page.dart';
import 'package:flutter_ar_project/home_page.dart';
import 'package:flutter_ar_project/notification_page.dart';
import 'package:flutter_ar_project/profile_page.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// ignore: prefer_const_constructors, prefer_const_literals_to_create_immutables
static final myColor = MaterialColor(0xffE63946, {
50: Color(0xffF6C6CB),
100: Color(0xffEEB4B9),
200: Color(0xffE69C9F),
300: Color(0xffDF8586),
400: Color(0xffDB6F6D),
500: Color(0xffE63946),
600: Color(0xffD31E2A),
700: Color(0xffB31B27),
800: Color(0xff931822),
900: Color(0xff7A0F1A),
});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const RootPage(
title: "AR Page",
),
theme: ThemeData(
primarySwatch: myColor,
),
debugShowCheckedModeBanner: false,
);
}
}
//
class RootPage extends StatefulWidget {
final String title;
const RootPage({Key? key, required this.title}) : super(key: key);
//const RootPage({super.key});
#override
State<RootPage> createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
int _selectedIndex = 0;
List<Widget> pages = const [
HomePage(),
DesignPage(),
NotificationsPage(),
ProfilePage(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: pages[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.folder_copy),
label: 'Design',
),
BottomNavigationBarItem(
icon: Icon(Icons.notifications),
label: 'Notifications',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
currentIndex: _selectedIndex,
type: BottomNavigationBarType.fixed,
selectedItemColor: const Color.fromARGB(255, 230, 57, 70),
onTap: _onItemTapped,
),
);
}
}
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.
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(),
],
),
);
}
}
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
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