Flutter is unable to display video - java

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');
}
},
),
),
);
}
}

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.

InvalidKeyException Error parsing public key java flutter

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

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.

Is it possible to get variable from Java class to a html file

I'd like to use the swaggerjson String, to define as a var in a html file.
private static BeanConfig beanConfig = new BeanConfig();
public EtelApplication() {
printPath();
beanConfig.setTitle("jim-rest");
beanConfig.setResourcePackage("com.mast.api");
beanConfig.setScan(true);
beanConfig.scanAndRead();
printSwaggerJson();
createSwaggerJsonFile();
}
private void printSwaggerJson() {
String swaggerjson = Json.pretty(beanConfig.getSwagger());
System.out.println(swaggerjson);
}
My html file has this script, where I would like to use the string
window.onload = function () {
const ui = SwaggerUIBundle({name */
url: "swagger.json", name: "jim-rest",
dom_id: '#swagger-ui',
validatorUrl: null,
deepLinking: true,
spec: swaggerjson, //this is where I would like to use the var.
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
is it possible to use swaggerjson directly like this?
I aplogise for the very simple question, I wasn't able to find a detailed answer when searching

ReactJS/Javascript: map function and rendering

The Graph component is getting data (verified in console) but for some reason the page is still blank. I am not quit sure I understand how the map function works. This is the last piece I need to figure out to render this graph but for whatever reason I can't seem to get any graphics on the screen. The state of nodes in the console is:
{data: {action: [{action: "Changed", timestamp: 1499348050,…},…]}}
data:{action: [{action: "Changed", timestamp: 1499348050,…},…]}
action:[{action: "User Assist Changed", timestamp: 1499348050,…},…]
Graph Component:
import React, {Component} from 'react';
import * as d3 from "d3";
import {graphql} from 'react-apollo';
import getObjectsQuery from './Queries';
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = { startTime:this.props.startTime,
endTime:this.props.endTime,
nodes:this.props.getObjectsQuery
}
//console.log('graph data:', this.props.data)
}
componentDidMount() {
console.log('nodes:', this.props.data)
this.force = d3.forceSimulation(this.props.data)
.force("charge",
d3.forceManyBody()
.strength(this.props.forceStrength)
)
.force("x", d3.forceX(this.props.width / 2))
.force("y", d3.forceY(this.props.height / 2));
this.force.on('tick', () => this.setState({nodes: this.props.data}));
console.log('setState:', this.props.data);
}
componentWillUnmount() {
this.force.stop();
}
render() {
// console.log('graph datas:', this.props.data)
return (
<svg width={this.props.width} height={this.props.height}>
{Object.keys(this.props.data).map((action, index) =>(
<circle r={action.action} cx={action.second} cy={action.obj} fill="red" key={index}/>
))}
</svg>
);
}//render
}//Component
export default graphql(getObjectsQuery,
{ options: (ownProps) => {
console.log(ownProps.startTime);
return ({ second: { startTime: ownProps.startTime,
endTime: ownProps.endTime
} })
} } )(Graph);
Graph.defaultProps = {
width: 300,
height: 300,
forceStrength: -10
};
If this.props.data.action is an array then it can be used directly in map:
{this.props.data.action.map((action,
but this.props.data.action (and even this.props.data?) can be undefined on start, first render
use some conditions in render to prevent errors, f.e.
{!this.props.data.loading && this.props.data.action.map((action,
Check if loading is present ... structure of props passed into component can be mapped differently by fn defined in config props property in graphql() (f.e. in case of conflict props names). Search for examples.

Categories

Resources