InvalidKeyException Error parsing public key java flutter - java

Am trying to encrypt messages using RSA Encryption from my flutter app. So I used flutter pointycastle package to generate RSA Public and Private Key Pairs and then am trying to use rsa encryption in java to encrypt and decrypt the message using the key pairs gotten from flutter ponitycastle. This is my error that i got.
D/OpenSSLLib(16468): OpensslErr:Module:6(102:); file:external/boringssl/src/crypto/evp/evp_asn1.c ;Line:110;Function:EVP_parse_public_key
W/System.err(16468): java.security.spec.InvalidKeySpecException: com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: Error parsing public key
W/System.err(16468): at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:281)
W/System.err(16468): at com.android.org.conscrypt.OpenSSLRSAKeyFactory.engineGeneratePublic(OpenSSLRSAKeyFactory.java:54)
W/System.err(16468): at java.security.KeyFactory.generatePublic(KeyFactory.java:361)
W/System.err(16468): at com.example.rsa.RSAUtil.getPublicKey(RSAUtil.java:19)
W/System.err(16468): at com.example.rsa.RSAUtil.encrypt(RSAUtil.java:48)
W/System.err(16468): at com.example.rsa.MainActivity.lambda$configureFlutterEngine$0(MainActivity.java:34)
W/System.err(16468): at com.example.rsa.-$$Lambda$MainActivity$83_j9v8T2k08fC4NjzAGyU_uVK0.onMethodCall(Unknown Source:0)
W/System.err(16468): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
W/System.err(16468): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
W/System.err(16468): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
W/System.err(16468): at android.os.MessageQueue.nativePollOnce(Native Method)
W/System.err(16468): at android.os.MessageQueue.next(MessageQueue.java:326)
W/System.err(16468): at android.os.Looper.loop(Looper.java:160)
W/System.err(16468): at android.app.ActivityThread.main(ActivityThread.java:6819)
W/System.err(16468): at java.lang.reflect.Method.invoke(Native Method)
W/System.err(16468): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
W/System.err(16468): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
W/System.err(16468): Caused by: com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: Error parsing public key
W/System.err(16468): at com.android.org.conscrypt.NativeCrypto.EVP_parse_public_key(Native Method)
JAVA CODE
my java code used was gotten from this link: RSA java encryption
FLUTTER CODE
While my flutter code to generate the keys is from here: Asymmetric Key Generation in Flutter
This is my flutter side
import 'package:flutter/services.dart';
import 'package:rsa/encrypt/rsa.dart';
Future<String> methodC(String channel,
{String priv, String pub, String msg}) async {
dynamic _message;
try {
dynamic result = await MethodChannel("com.example.rsa/callback")
.invokeMethod("encryptMsg", <String, dynamic>{
"priv": RSA().removePemHeaderAndFooter(priv),
"pub": RSA().removePemHeaderAndFooter(pub),
"msg": msg
});
_message = result;
} on PlatformException catch (e) {
_message = e.message.toString();
} catch (e) {
_message = e.message.toString();
}
print(_message);
return _message;
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rsa/constant.dart';
import 'package:rsa/encrypt/rsa.dart';
import 'package:pointycastle/api.dart' as crypto;
class RSAHome extends StatefulWidget {
const RSAHome({Key key}) : super(key: key);
#override
_RSAHomeState createState() => _RSAHomeState();
}
class _RSAHomeState extends State<RSAHome> {
Future<String> futureText;
/// Future to hold the reference to the KeyPair generated with PointyCastle
/// in order to extract the [crypto.PrivateKey] and [crypto.PublicKey]
Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>>
futureKeyPair;
/// The current [crypto.AsymmetricKeyPair]
crypto.AsymmetricKeyPair keyPair;
/// With the helper [RsaKeyHelper] this method generates a
/// new [crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>
Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>>
getKeyPair() {
var keyHelper = RSA();
return keyHelper.computeRSAKeyPair(keyHelper.getSecureRandom());
}
/// GlobalKey to be used when showing the [Snackbar] for the successful
/// copy of the Key
final key = new GlobalKey<ScaffoldState>();
/// Text Editing Controller to retrieve the text to sign
TextEditingController _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
key: key,
appBar: AppBar(
title: Text("Get Key"),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
"Generate new Key Pair",
),
onPressed: () {
setState(() {
// If there are any pemString being shown, then show an empty message
futureText = Future.value("");
// Generate a new keypair
futureKeyPair = getKeyPair();
});
},
),
Expanded(
child: FutureBuilder<
crypto.AsymmetricKeyPair<crypto.PublicKey,
crypto.PrivateKey>>(
future: futureKeyPair,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// if we are waiting for a future to be completed, show a progress indicator
return Center(child: CircularProgressIndicator());
} else if (snapshot.hasData) {
// Else, store the new keypair in this state and sbow two buttons
this.keyPair = snapshot.data;
return ListView(
children: <Widget>[
MaterialButton(
color: Colors.red,
child: Text(
"Get Private Key",
),
onPressed: () {
setState(() {
// With the stored keypair, encode the private key to
// PKCS1 and show it
futureText = Future.value(RSA()
.encodePrivateKeyToPemPKCS1(
keyPair.privateKey));
});
},
),
MaterialButton(
color: Colors.green,
child: Text("Get Public Key"),
onPressed: () {
setState(() {
// With the stored keypair, encode the public key to
// PKCS1 and show it
futureText = Future.value(RSA()
.encodePublicKeyToPemPKCS1(
keyPair.publicKey));
});
},
),
TextField(
decoration:
InputDecoration(hintText: "Text to Sign"),
controller: _controller,
),
MaterialButton(
color: Colors.red,
child: Text(
"Sign Text",
),
onPressed: () {
setState(() {
futureText = Future.value(RSA().sign(
_controller.text, keyPair.privateKey));
});
},
),
MaterialButton(
color: Colors.red,
child: Text(
"Encrypt",
),
onPressed: () async {
futureText = methodC("encryptMsg",
priv: await futureText,
pub: await futureText,
msg: _controller.text);
setState(() {});
},
),
MaterialButton(
color: Colors.red,
child: Text(
"Decrypt",
),
onPressed: () {
setState(() {
setState(() async {
futureText = Future.value(methodC(
"decryptMsg",
priv: await futureText,
pub: await futureText,
msg: _controller.text));
});
});
},
),
],
);
} else {
return Container();
}
}),
),
Expanded(
child: Card(
child: Container(
padding: EdgeInsets.all(8),
margin: EdgeInsets.all(8),
child: FutureBuilder(
future: futureText,
builder: (context, snapshot) {
if (snapshot.hasData) {
return SingleChildScrollView(
// the inkwell is used to register the taps
// in order to be able to copy the text
child: InkWell(
onTap: () {
// Copies the data to the keyboard
Clipboard.setData(
new ClipboardData(text: snapshot.data));
key.currentState.showSnackBar(new SnackBar(
content: new Text("Copied to Clipboard"),
));
},
child: Text(snapshot.data)),
);
} else {
return Center(
child: Text("Your keys will appear here"),
);
}
}),
),
),
)
],
),
),
),
));
}
}
AND MY Java side
package com.example.rsa;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.embedding.android.FlutterActivity;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL_NAME_CALL = "com.example.rsa/callback";
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL_NAME_CALL)
.setMethodCallHandler(
(call, result) -> {
RSAUtil rsa = new RSAUtil();
String pubKey = call.argument("pub");
String privKey = call.argument("priv");
String msg = call.argument("msg");
if(call.method.equals("encryptMsg")) {
try {
String encryptedString = Base64.getEncoder().encodeToString(rsa.encrypt(msg, pubKey));
result.success(encryptedString);
}catch(BadPaddingException bad){
result.error("Catch BadPaddingException", "BadPaddingException error", null);
}
catch(IllegalBlockSizeException bad){
result.error("Catch IllegalBlockSizeException", "IllegalBlockSizeException error", null);
}
catch(InvalidKeyException bad){
result.error("Catch InvalidKeyException", "InvalidKeyException error", null);
}
catch(NoSuchPaddingException bad){
result.error("Catch NoSuchPaddingException", "NoSuchPaddingException error", null);
}
catch(NoSuchAlgorithmException bad){
result.error("Catch NoSuchAlgorithmException", "NoSuchAlgorithmException error", null);
}
}
else if(call.method.equals("decryptMsg")) {
// String decryptedString = rsa.decrypt(encryptedString, privateKey);
result.success(pubKey);
}
result.notImplemented();
return;
}
);
}
}
Please help me out guys and if there is something you want me to add you can ask me to provide. Please

Related

Amazon Location map how to enable Route calculator, tracker map in react js project

I need your help to implement the AWS map, I have created the Arn for all the required map functionality but I don't know how to enable the search box and its functionality.
Map --> implemented
Place index --> need help
Route calculator --> need help
Geofence collection --> need help
Tracker --> need help
sample code for your reference:
import React, { useEffect, useState } from "react";
import { createRequestTransformer } from "amazon-location-helpers";
import { ICredentials } from "#aws-amplify/core";
import Amplify,{ Auth } from "aws-amplify";
import ReactMapGL, { NavigationControl, ViewportProps } from "react-map-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import amplifyConfig from "../aws-exports";
Amplify.configure(amplifyConfig);
// Replace with the name of the map that you created on the Amazon Location Service console: https://console.aws.amazon.com/location/maps/home
const mapName = "<MAP NAME>";
const Map = () => {
const [credentials, setCredentials] = useState<ICredentials>();
const [transformRequest, setRequestTransformer] = useState<Function>();
const [viewport, setViewport] = React.useState<Partial<ViewportProps>>({
longitude: -123.1187,
latitude: 49.2819,
zoom: 10,
});
useEffect(() => {
const fetchCredentials = async () => {
setCredentials(await Auth.currentUserCredentials());
};
fetchCredentials();
}, []);
// create a new transformRequest function whenever the credentials change
useEffect(() => {
const makeRequestTransformer = async () => {
if (credentials != null) {
const tr = await createRequestTransformer({
credentials,
region: amplifyConfig.aws_project_region,
});
// wrap the new value in an anonymous function to prevent React from recognizing it as a
// function and immediately calling it
setRequestTransformer(() => tr);
}
};
makeRequestTransformer();
}, [credentials]);
return (
<div>
{transformRequest ? (
<ReactMapGL
{...viewport}
width="100%"
height="100vh"
/** #ts-ignore */
transformRequest={transformRequest}
mapStyle={mapName}
onViewportChange={setViewport}
>
<div style={{ position: "absolute", left: 20, top: 20 }}>
<NavigationControl showCompass={false} />
</div>
</ReactMapGL>
) : (
<h1>Loading...</h1>
)}
</div>
);
};
export default Map;
reference image:
I don't know how to enable the tracker and place index functionality can I get anyone help on this. Thanks in advance.

Flutter is unable to display video

import 'package:video_player/video_player.dart';
import 'package:flutter/material.dart';
void main() => runApp(VideoApp());
class VideoApp extends StatefulWidget {
#override
_VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
VideoPlayerController _controller;
#override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Demo',
home: Scaffold(
body: Center(
child: _controller.value.isInitialized
? AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
)
: Container(),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_controller.value.isPlaying
? _controller.pause()
: _controller.play();
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
),
);
}
#override
void dispose() {
super.dispose();
_controller.dispose();
}
}
Even though I had tried adding the dependencies and change the video link to a YouTube link instead, it still the same and does not display the video. May I know how to solve this problem? There are a few errors, I listed it as below:
The method 'VideoPlayer' isn't defined for the type '_VideoAppState'
Undefined name 'VideoPlayerController'.
Undefined class 'VideoPlayerController'.
Target of URI doesn't exist: 'package:video_player/video_player.dart'
Pubspec.yml below
name: icseat
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
dio: ^4.0.0
file_picker: ^4.0.0
video_player:
advance_pdf_viewer: ^2.0.0
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/logoicseat.png
- images/person.png
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
#Tommie C. The below are the errors that I experienced when running the codes:
Launching lib\View\Video.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:57805/tl8ztZ-XWag=/ws
Syncing files to device sdk gphone x86 arm...
W/e.icseattestin( 4832): Accessing hidden method Landroid/media/AudioTrack;->getLatency()I (greylist, reflection, allowed)
I/ExoPlayerImpl( 4832): Init bda4bd9 [ExoPlayerLib/2.14.1] [generic_x86_arm, sdk_gphone_x86_arm, Google, 30]
I/Choreographer( 4832): Skipped 54 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer( 4832): Davey! duration=921ms; Flags=0, IntendedVsync=313961916316, Vsync=314861916280, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=314868026700, AnimationStart=314868094000, PerformTraversalsStart=314871530500, DrawStart=314873232800, SyncQueued=314874438400, SyncStart=314875924800, IssueDrawCommandsStart=314875998400, SwapBuffers=314879263000, FrameCompleted=314885090400, DequeueBufferDuration=1230100, QueueBufferDuration=3509200, GpuCompleted=0,
I/TetheringManager( 4832): registerTetheringEventCallback:com.example.icseattesting
I/VideoCapabilities( 4832): Unsupported profile 4 for video/mp4v-es
I/OMXClient( 4832): IOmx service obtained
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason connectToSurface
I/MediaCodec( 4832): [OMX.android.goldfish.h264.decoder] setting surface generation to 4947969
D/SurfaceUtils( 4832): disconnecting from surface 0xe4d1c578, reason connectToSurface(reconnect)
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason connectToSurface(reconnect)
E/ACodec ( 4832): [OMX.android.goldfish.h264.decoder] setPortMode on output to DynamicANWBuffer failed w/ err -1010
I/ACodec ( 4832): codec does not support config priority (err -1010)
D/SurfaceUtils( 4832): disconnecting from surface 0xe4d1c578, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils( 4832): connecting to surface 0xe4d1c578, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils( 4832): set up nativeWindow 0xe4d1c578 for 1280x720, color 0x13, rotation 0, usage 0x1002900
W/Gralloc4( 4832): allocator 3.x is not supported
Lost connection to device.
Update:
Nota Bene: In the sample below, you can comment out the line trying to load the srt subtitles file (closedCaptionFile: _loadCaptions,).
Change the following in your pubspec.yaml to video_player: ^2.1.15
Note - Also, are you trying to run this in iOS or Android? Make sure you open
the Runner.xcworkspace file and perform the standard Xcode routines. Make
sure that the Runner project and the pods project is visible. Try
running flutter build ios from the terminal.
Then re-run flutter pub get or click get Dependencies in the UI. I'd also make a demo project (stub - flutter create --org com.yoursite stub01) and add the sample provided to see if the online sample is working.
Original:
Here is the complete sample from the plugin website for the video_player. You can paste it into your environment to be certain that everything is working. You should also make sure that you are following the setup steps where you give your iOS/Android app permission to access the internet (see the installation notes on the readme section of the website). I'd also make sure to run flutter upgrade on your terminal.
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
/// An example of using the plugin, controlling lifecycle and playback of the
/// video.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() {
runApp(
MaterialApp(
home: _App(),
),
);
}
class _App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
key: const ValueKey<String>('home_page'),
appBar: AppBar(
title: const Text('Video player example'),
actions: <Widget>[
IconButton(
key: const ValueKey<String>('push_tab'),
icon: const Icon(Icons.navigation),
onPressed: () {
Navigator.push<_PlayerVideoAndPopPage>(
context,
MaterialPageRoute<_PlayerVideoAndPopPage>(
builder: (BuildContext context) => _PlayerVideoAndPopPage(),
),
);
},
)
],
bottom: const TabBar(
isScrollable: true,
tabs: <Widget>[
Tab(
icon: Icon(Icons.cloud),
text: "Remote",
),
Tab(icon: Icon(Icons.insert_drive_file), text: "Asset"),
Tab(icon: Icon(Icons.list), text: "List example"),
],
),
),
body: TabBarView(
children: <Widget>[
_BumbleBeeRemoteVideo(),
_ButterFlyAssetVideo(),
_ButterFlyAssetVideoInList(),
],
),
),
);
}
}
class _ButterFlyAssetVideoInList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
_ExampleCard(title: "Item a"),
_ExampleCard(title: "Item b"),
_ExampleCard(title: "Item c"),
_ExampleCard(title: "Item d"),
_ExampleCard(title: "Item e"),
_ExampleCard(title: "Item f"),
_ExampleCard(title: "Item g"),
Card(
child: Column(children: <Widget>[
Column(
children: <Widget>[
const ListTile(
leading: Icon(Icons.cake),
title: Text("Video video"),
),
Stack(
alignment: FractionalOffset.bottomRight +
const FractionalOffset(-0.1, -0.1),
children: <Widget>[
_ButterFlyAssetVideo(),
Image.asset('assets/flutter-mark-square-64.png'),
]),
],
),
])),
_ExampleCard(title: "Item h"),
_ExampleCard(title: "Item i"),
_ExampleCard(title: "Item j"),
_ExampleCard(title: "Item k"),
_ExampleCard(title: "Item l"),
],
);
}
}
/// A filler card to show the video in a list of scrolling contents.
class _ExampleCard extends StatelessWidget {
const _ExampleCard({Key? key, required this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: const Icon(Icons.airline_seat_flat_angled),
title: Text(title),
),
ButtonBar(
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {
/* ... */
},
),
TextButton(
child: const Text('SELL TICKETS'),
onPressed: () {
/* ... */
},
),
],
),
],
),
);
}
}
class _ButterFlyAssetVideo extends StatefulWidget {
#override
_ButterFlyAssetVideoState createState() => _ButterFlyAssetVideoState();
}
class _ButterFlyAssetVideoState extends State<_ButterFlyAssetVideo> {
late VideoPlayerController _controller;
#override
void initState() {
super.initState();
_controller = VideoPlayerController.asset('assets/Butterfly-209.mp4');
_controller.addListener(() {
setState(() {});
});
_controller.setLooping(true);
_controller.initialize().then((_) => setState(() {}));
_controller.play();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.only(top: 20.0),
),
const Text('With assets mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller, allowScrubbing: true),
],
),
),
),
],
),
);
}
}
class _BumbleBeeRemoteVideo extends StatefulWidget {
#override
_BumbleBeeRemoteVideoState createState() => _BumbleBeeRemoteVideoState();
}
class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> {
late VideoPlayerController _controller;
Future<ClosedCaptionFile> _loadCaptions() async {
final String fileContents = await DefaultAssetBundle.of(context)
.loadString('assets/bumble_bee_captions.srt');
return SubRipCaptionFile(fileContents);
}
#override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4',
// closedCaptionFile: _loadCaptions(),
videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
);
_controller.addListener(() {
setState(() {});
});
_controller.setLooping(true);
_controller.initialize();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
Container(padding: const EdgeInsets.only(top: 20.0)),
const Text('With remote mp4'),
Container(
padding: const EdgeInsets.all(20),
child: AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
VideoPlayer(_controller),
ClosedCaption(text: _controller.value.caption.text),
_ControlsOverlay(controller: _controller),
VideoProgressIndicator(_controller, allowScrubbing: true),
],
),
),
),
],
),
);
}
}
class _ControlsOverlay extends StatelessWidget {
const _ControlsOverlay({Key? key, required this.controller})
: super(key: key);
static const _examplePlaybackRates = [
0.25,
0.5,
1.0,
1.5,
2.0,
3.0,
5.0,
10.0,
];
final VideoPlayerController controller;
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
AnimatedSwitcher(
duration: Duration(milliseconds: 50),
reverseDuration: Duration(milliseconds: 200),
child: controller.value.isPlaying
? SizedBox.shrink()
: Container(
color: Colors.black26,
child: Center(
child: Icon(
Icons.play_arrow,
color: Colors.white,
size: 100.0,
),
),
),
),
GestureDetector(
onTap: () {
controller.value.isPlaying ? controller.pause() : controller.play();
},
),
Align(
alignment: Alignment.topRight,
child: PopupMenuButton<double>(
initialValue: controller.value.playbackSpeed,
tooltip: 'Playback speed',
onSelected: (speed) {
controller.setPlaybackSpeed(speed);
},
itemBuilder: (context) {
return [
for (final speed in _examplePlaybackRates)
PopupMenuItem(
value: speed,
child: Text('${speed}x'),
)
];
},
child: Padding(
padding: const EdgeInsets.symmetric(
// Using less vertical padding as the text is also longer
// horizontally, so it feels like it would need more spacing
// horizontally (matching the aspect ratio of the video).
vertical: 12,
horizontal: 16,
),
child: Text('${controller.value.playbackSpeed}x'),
),
),
),
],
);
}
}
class _PlayerVideoAndPopPage extends StatefulWidget {
#override
_PlayerVideoAndPopPageState createState() => _PlayerVideoAndPopPageState();
}
class _PlayerVideoAndPopPageState extends State<_PlayerVideoAndPopPage> {
late VideoPlayerController _videoPlayerController;
bool startedPlaying = false;
#override
void initState() {
super.initState();
_videoPlayerController =
VideoPlayerController.asset('assets/Butterfly-209.mp4');
_videoPlayerController.addListener(() {
if (startedPlaying && !_videoPlayerController.value.isPlaying) {
Navigator.pop(context);
}
});
}
#override
void dispose() {
_videoPlayerController.dispose();
super.dispose();
}
Future<bool> started() async {
await _videoPlayerController.initialize();
await _videoPlayerController.play();
startedPlaying = true;
return true;
}
#override
Widget build(BuildContext context) {
return Material(
elevation: 0,
child: Center(
child: FutureBuilder<bool>(
future: started(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.data == true) {
return AspectRatio(
aspectRatio: _videoPlayerController.value.aspectRatio,
child: VideoPlayer(_videoPlayerController),
);
} else {
return const Text('waiting for video to load');
}
},
),
),
);
}
}

Widget for Home screen of Mobile App in flutter

I am trying to Implement Home Screen Widget with flutter, this is the package i am trying to use home_widget but unfortunately I run into some exceptions i could not understand.
here is the my code,
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:home_widget/home_widget.dart';
import 'package:workmanager/workmanager.dart';
/// Used for Background Updates using Workmanager Plugin
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) {
final now = DateTime.now();
return Future.wait<bool?>([
HomeWidget.saveWidgetData(
'title',
'Updated from Background',
),
HomeWidget.saveWidgetData(
'message',
'${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}',
),
HomeWidget.updateWidget(
name: 'HomeWidgetExampleProvider',
iOSName: 'HomeWidgetExample',
),
]).then((value) {
return !value.contains(false);
});
});
}
/// Called when Doing Background Work initiated from Widget
void backgroundCallback(var data) async {
print(data);
if (data.host == 'titleclicked') {
final greetings = [
'Hello',
'Hallo',
'Bonjour',
'Hola',
'Ciao',
'哈洛',
'안녕하세요',
'xin chào'
];
final selectedGreeting = greetings[Random().nextInt(greetings.length)];
await HomeWidget.saveWidgetData<String>('title', selectedGreeting);
await HomeWidget.updateWidget(
name: 'HomeWidgetExampleProvider', iOSName: 'HomeWidgetExample');
}
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
Workmanager().initialize(callbackDispatcher, isInDebugMode: kDebugMode);
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final TextEditingController _titleController = TextEditingController();
final TextEditingController _messageController = TextEditingController();
#override
void initState() {
super.initState();
HomeWidget.setAppGroupId('YOUR_GROUP_ID');
HomeWidget.registerBackgroundCallback(backgroundCallback);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
_checkForWidgetLaunch();
HomeWidget.widgetClicked.listen(_launchedFromWidget);
}
#override
void dispose() {
_titleController.dispose();
_messageController.dispose();
super.dispose();
}
Future _sendData() async {
try {
return Future.wait([
HomeWidget.saveWidgetData<String>('title', _titleController.text),
HomeWidget.saveWidgetData<String>('message', _messageController.text),
]);
} on PlatformException catch (exception) {
debugPrint('Error Sending Data. $exception');
}
}
Future _updateWidget() async {
try {
return HomeWidget.updateWidget(
name: 'HomeWidgetExampleProvider', iOSName: 'HomeWidgetExample');
} on PlatformException catch (exception) {
debugPrint('Error Updating Widget. $exception');
}
}
Future _loadData() async {
try {
return Future.wait([
HomeWidget.getWidgetData<String>('title', defaultValue: 'Default Title')
.then((value) => _titleController.text = value.toString()),
HomeWidget.getWidgetData<String>('message',
defaultValue: 'Default Message')
.then((value) => _messageController.text = value.toString()),
]);
} on PlatformException catch (exception) {
debugPrint('Error Getting Data. $exception');
}
}
Future<void> _sendAndUpdate() async {
await _sendData();
await _updateWidget();
}
void _checkForWidgetLaunch() {
HomeWidget.initiallyLaunchedFromHomeWidget().then(_launchedFromWidget);
}
void _launchedFromWidget(var uri) {
if (uri != null) {
showDialog(
context: context,
builder: (buildContext) => AlertDialog(
title: Text('App started from HomeScreenWidget'),
content: Text('Here is the URI: $uri'),
));
}
}
void _startBackgroundUpdate() {
Workmanager().registerPeriodicTask('1', 'widgetBackgroundUpdate',
frequency: Duration(minutes: 15));
}
void _stopBackgroundUpdate() {
Workmanager().cancelByUniqueName('1');
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HomeWidget Example'),
),
body: Center(
child: Column(
children: [
TextField(
decoration: InputDecoration(
hintText: 'Title',
),
controller: _titleController,
),
TextField(
decoration: InputDecoration(
hintText: 'Body',
),
controller: _messageController,
),
ElevatedButton(
onPressed: _sendAndUpdate,
child: Text('Send Data to Widget'),
),
ElevatedButton(
onPressed: _loadData,
child: Text('Load Data'),
),
ElevatedButton(
onPressed: _checkForWidgetLaunch,
child: Text('Check For Widget Launch'),
),
if (Platform.isAndroid)
ElevatedButton(
onPressed: _startBackgroundUpdate,
child: Text('Update in background'),
),
if (Platform.isAndroid)
ElevatedButton(
onPressed: _stopBackgroundUpdate,
child: Text('Stop updating in background'),
)
],
),
),
);
}
}
and here are the exceptions i am getting,
E/flutter (16907): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(error, java.lang.Integer cannot be cast to java.lang.Long, null, java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
E/flutter (16907): at es.antonborri.home_widget.HomeWidgetPlugin.onMethodCall(HomeWidgetPlugin.kt:105)
E/flutter (16907): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/flutter (16907): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/flutter (16907): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/flutter (16907): at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (16907): at android.os.MessageQueue.next(MessageQueue.java:336)
E/flutter (16907): at android.os.Looper.loop(Looper.java:174)
E/flutter (16907): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/flutter (16907): at java.lang.reflect.Method.invoke(Native Method)
E/flutter (16907): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/flutter (16907): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter (16907): )
E/flutter (16907): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter (16907): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
E/flutter (16907): <asynchronous suspension>
E/flutter (16907):
The exception saying "PlatformException(error, java.lang.Integer cannot be cast to java.lang.Long, null, java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long" is what i can not understand. I have copied and pated exact documentation code too but it contains some errors that were corrected in above given code by me.
any help whould be great. thanks

E/GraphResponse: Unsupported get request. Android Studio facebook login

I have problem with Facebook login app. I was fallowing this tutorial . I took every step and on the end i converted MainAcktivity into kotlin file. Application after login in or logout is stopping.
and I'm receiving follow error in Logcat:
2021-05-22 19:23:12.963 9521-9545/com.example.XXX_login E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request. Object with ID '111111111111111' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}
2021-05-22 19:23:46.065 9521-9521/com.example.XXX_login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.XXX_login, PID: 9521
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter oldAccessToken
at com.example.XXX_login.MainActivity$accessTokenTracker$1.onCurrentAccessTokenChanged(Unknown Source:2)
at com.facebook.AccessTokenTracker$CurrentAccessTokenBroadcastReceiver.onReceive(AccessTokenTracker.java:110)
at androidx.localbroadcastmanager.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:313)
at androidx.localbroadcastmanager.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:121)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Here is my MainActivity.kt file:
package com.example.XXX_login
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.facebook.login.widget.LoginButton
import org.json.JSONException
import com.squareup.picasso.Picasso as Picasso1
//import java.util.*
class MainActivity : AppCompatActivity() {
private var callbackManager: CallbackManager? = null
private lateinit var loginButton: LoginButton
private var imageView: ImageView? = null
private var textView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loginButton = findViewById(R.id.login_button)
textView = findViewById(R.id.tv_name)
imageView = findViewById(R.id.tv_profilePic)
callbackManager = CallbackManager.Factory.create()
//permisions do logowania
loginButton.setPermissions(
listOf(
"user_gender",
"email",
"user_location",
"user_birthday"
)
)
loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult?> {
override fun onSuccess(loginResult: LoginResult?) {
Log.d("Demo", "Zalogowano!")
}
override fun onCancel() {
Log.d("Demo", "Wylogowano")
}
override fun onError(error: FacebookException) {
Log.d("Demo", "Bład logowania:")
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
callbackManager!!.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
val graphRequest =
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken()) { `object`, response ->
//tworzenie pliku JSON z pobieranymi przez Graph danymi
Log.d("Demo", `object`.toString())
try {
val name = `object`.getString("name")
val pic = `object`.getJSONObject("picture").getJSONObject("data").getString("url")
textView!!.text = name
Picasso1.get().load(pic).into(imageView)
} catch (e: JSONException) {
e.printStackTrace()
}
}
val bundle = Bundle()
//informacjie pozyskiwane z facebooka= defaultowe i na podstawie wcześniej wydanych permissions
bundle.putString(
"fields",
"gender, name, first_name, last_name, email, birthday, location, picture"
)
graphRequest.parameters = bundle
graphRequest.executeAsync()
}
//tracker do sprawdzania czy użytkownik jest zalogowany, jestli token sie zmieni to wywowała sie ta metoda
//wylogowywanie sie
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken,
currentAccessToken: AccessToken
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
override fun onDestroy() {
super.onDestroy()
accessTokenTracker.stopTracking()
}
}
I had have read in the internet for answer for this problem but i've could't find something that could work.
This is because in Kotlin you have to specify the variable as nullable if it will be null in any case.
The error is in this function
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken,
currentAccessToken: AccessToken
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
here in the onCurrentAccessTokenChanged() function you are expecting the currentAccessToken to be null, but you have not made currentAccessToken as nullable hence it will fail and crash. Since only nullable elements can get null value assigned after initialisation in Kotlin. Therefore here you can make the variables as nullable and the problem will be solved.
You can make any variable as nullable like this
currentAccessToken : Type? , where the Type can be Int, String or any supported or custom type.
var accessTokenTracker: AccessTokenTracker = object : AccessTokenTracker() {
override fun onCurrentAccessTokenChanged(
oldAccessToken: AccessToken?,
currentAccessToken: AccessToken?
) {
if (currentAccessToken == null) {
LoginManager.getInstance().logOut()
textView!!.text = ""
imageView!!.setImageResource(0)
}
}
}
This will solve your problem.
It is always recommended that you make the variables as Nullable if you think that the variable might accommodate null at any time in the future in any case to avoid such crashes.

Unhandled Exception: PlatformException (sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) - works well in one system

I am developing a Bluetooth application using platform channel in flutter (using Java). But while I try to login with google-sign in( google_sign_in: ^4.5.6 ) I'm getting the error.
I can login the details but I can't move to further page......
Actually, it's working in my office system, but when I copy the project and run in another it gives the error...Can anyone please help
main.dart
import 'package:bmsapp2/pages/loginpage.dart';
import 'package:flutter/material.dart';
void main() {
runApp(BmsApp());
}
class BmsApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
const curveHeight = 12.0;
return MaterialApp(
home: SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.amber[900],
shape: const MyShapeBorder(curveHeight),
),
body: LoginPage(),
),
),
);
}
}
class MyShapeBorder extends ContinuousRectangleBorder {
const MyShapeBorder(this.curveHeight);
final double curveHeight;
#override
Path getOuterPath(Rect rect, {TextDirection textDirection}) => Path()
..lineTo(0, rect.size.height)
..quadraticBezierTo(
rect.size.width / 2,
rect.size.height + curveHeight * 2,
rect.size.width,
rect.size.height,
)
..lineTo(rect.size.width, 0)
..close();
}
loginpage.dart
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:avatar_glow/avatar_glow.dart';
import 'bluetoothpage.dart';
final GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['profile', 'email']);
class LoginPage extends StatefulWidget {
LoginPage({Key key}) : super(key: key);
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
bool isAuth = false;
GoogleSignInAccount _currentUser;
Widget buildAuthScreen() {
//return Text(_currentUser.displayName ?? '');
return SafeArea(
child: Center(
child: Container(
margin: EdgeInsets.only(top: 50),
child: Column(
//mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundColor: Colors.white,
backgroundImage: NetworkImage(_currentUser.photoUrl),
radius: 50,
),
SizedBox(height: 15),
Text(
'You are logged in as ',
style: TextStyle(
color: Colors.grey,
fontSize: 15,
),
),
SizedBox(height: 5),
Text(
_currentUser.email,
style: TextStyle(
color: Colors.black,
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
ElevatedButton(
onPressed: _logout,
child: Text("Logout".toUpperCase(),
style: TextStyle(fontSize: 14, letterSpacing: 2)),
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all<Color>(Colors.white),
backgroundColor:
MaterialStateProperty.all<Color>(Colors.amber[900]),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
side: BorderSide(color: Colors.amber[900])))),
),
Container(
// height: 300,
child: AvatarGlow(
glowColor: Colors.blue,
endRadius: 70.0,
duration: Duration(milliseconds: 2000),
repeat: true,
showTwoGlows: true,
repeatPauseDuration: Duration(milliseconds: 100),
child: Material(
elevation: 4.0,
shape: CircleBorder(),
child: CircleAvatar(
backgroundColor: Colors.grey[200],
child: Image.asset(
'images/bt.png',
height: 40,
width: 250,
fit: BoxFit.fitWidth,
),
radius: 40.0,
),
),
),
),
ElevatedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => BluetoothPage()));
},
child: Text('Find your device',
style: TextStyle(fontSize: 15, letterSpacing: 2)),
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all<Color>(Colors.white),
backgroundColor:
MaterialStateProperty.all<Color>(Colors.amber[900]),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
side: BorderSide(color: Colors.amber[900])))),
),
],
),
),
),
);
}
_login() {
googleSignIn.signIn();
}
_logout() {
googleSignIn.signOut();
}
Widget buildUnAuthScreen() {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
child: Image.asset('images/touch.png'),
),
SizedBox(
height: 5.0,
),
Text(
'Next Generation Battery',
style: TextStyle(fontSize: 15, color: Colors.grey),
),
SizedBox(
height: 5.0,
),
Container(
child: GestureDetector(
onTap: () {
_login();
},
child: Image.asset(
'images/signin.png',
height: 75,
width: 250,
fit: BoxFit.fitWidth,
),
),
),
Text(
'Sign up here',
style: TextStyle(fontSize: 15, color: Colors.grey),
),
],
),
));
}
void handleSignin(GoogleSignInAccount account) {
if (account != null) {
print('User Signed in $account');
setState(() {
isAuth = true;
_currentUser = account;
});
} else {
setState(() {
isAuth = false;
//_currentUser = null;
});
}
}
#override
void initState() {
super.initState();
googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
handleSignin(account);
}, onError: (err) {
print('Error Signiing in : $err');
});
// Reauthenticate user when app is opened
/*googleSignIn.signInSilently(suppressErrors: false).then((account) {
handleSignin(account);
}).catchError((err) {
print('Error Signiing in : $err');
});*/
}
#override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : buildUnAuthScreen();
}
}
error:
E/flutter (12476): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null)
E/flutter (12476): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:581
E/flutter (12476): #1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:158
E/flutter (12476): <asynchronous suspension>
E/flutter (12476): #2 MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:358
E/flutter (12476): <asynchronous suspension>
E/flutter (12476):
D/ViewRootImpl#4370975[SignInHubActivity](12476): mHardwareRenderer.destroy()#1
D/ViewRootImpl#4370975[SignInHubActivity](12476): Relayout returned: oldFrame=[0,0][1440,2560] newFrame=[0,0][1440,2560] result=0x5 surface={isValid=false 0} surfaceGenerationChanged=true
D/ViewRootImpl#4370975[SignInHubActivity](12476): mHardwareRenderer.destroy()#4
D/ViewRootImpl#4370975[SignInHubActivity](12476): dispatchDetachedFromWindow
D/InputTransport(12476): Input channel destroyed: fd=102
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null, null) apiException:10 means it's most likely due to incorrect setup of SHA-1 or SHA-256. Since you said that it works at the office, it's probably a different environment than what you are working with now, and you should add these keys. This is also assuming that you are running a debug build, so add your debugging SHA-1 keys.
Also this problem happens with the apps downloaded from Google Play. This is because Google signs your app with it's own key which is not accessible for you. You can get it's SHA1 from: Google Play Console -> Your App -> App Integrity.
Recently fixed this issue after many tries, After updating to flutter-3.1.0-pre9, and Updating Android studio to chipmunk 2021.2.1, I got an interesting debug message.
The google sign in works well on iOS, but no matter what I did, I keep getting this exact message PlatformException (sign_in_failed... blah blah blah
The new error message now has this also: clientId is not supported on Android and is interpreted as serverClientId. Use serverClientId
Adding clientId as the parameter on Android seems to be the problem
Make sure your keystore sha-1 is registered on firebase and you have completed the instructions as stated on firebase
late GoogleSignIn googleSignIn;
***
#override
void initState() {
***
googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/userinfo.profile',
],
serverClientId: isIOS ? null : googleClientId,
clientId: isIOS ? googleClientIdIOS : null);
***
This way you set clientId while on iOS and serverClientId on Android.
Hope this help.

Categories

Resources