i get this error when trying to fetch and store location in local database
this is my homepage.dart
import 'package:attendance_app/local_database/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:toast/toast.dart';
import 'package:attendance_app/local_database/database.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _buttonEnabled = true;
Position _currentPosition;
String _formattedDate;
DataBaseHelper helper;
#override
void initState() {
// TODO: implement initState
super.initState();
_getCurrentLocation();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: Colors.white),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 55.0,
width: 150.0,
color: Colors.lightGreen,
child: RaisedButton(
elevation: 0,
textColor: Colors.white,
splashColor: Colors.amber,
disabledColor: Colors.grey,
child: Text(
"Head start",
textScaleFactor: 1.6,
),
color: Colors.lightGreen,
onPressed: () async {
_getCurrentLocation();
_getDateTime();
_insertToDb(createDataBaseObj(
'IN',
_currentPosition.latitude.toString(),
_currentPosition.longitude.toString(),
_formattedDate));
Toast.show("$_currentPosition , $_formattedDate", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
},
),
),
SizedBox(
height: 20.0,
),
Container(
height: 55.0,
width: 150.0,
color: Colors.red[300],
child: RaisedButton(
elevation: 0,
textColor: Colors.white,
splashColor: Colors.amber,
disabledColor: Colors.grey,
child: Text(
"Check out",
textScaleFactor: 1.6,
),
color: Colors.red[300],
onPressed: () async {
_getCurrentLocation();
_getDateTime();
_insertToDb(createDataBaseObj(
'OUT',
_currentPosition.latitude.toString(),
_currentPosition.longitude.toString(),
_formattedDate));
Toast.show(
"$_currentPosition , $_formattedDate", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
},
)),
]),
),
bottomNavigationBar: Container(
height: 55.0,
color: _buttonEnabled ? Colors.green : Colors.grey,
child: RaisedButton(
elevation: 0,
textColor: Colors.white,
splashColor: Colors.amber,
disabledColor: Colors.grey,
child: Text(
"sync",
textScaleFactor: 1.6,
),
color: Colors.green,
onPressed: () async {},
)));
}
_getCurrentLocation() async {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
await geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
print(position);
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
_getDateTime() {
DateTime now = DateTime.now();
String formattedDate = DateFormat('kk:mm:ss EEE d MMM').format(now);
setState(() {
_formattedDate = formattedDate;
});
}
DataBase createDataBaseObj(type, lat, long, time) {
DataBase result = DataBase(type, lat, long, time);
print('createDataBaseObj');
print(result.toMap());
return result;
}
void _insertToDb(DataBase dataBase) async {
var value = await helper.insertData(dataBase);
print(value);
}
void _delete(BuildContext context, DataBase dataBase) async {
await helper.deleteData(dataBase.id);
}
}
this is database_helper.dart file
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'database.dart';
class DataBaseHelper {
static DataBaseHelper _dataBaseHelper;
static Database _database;
String table = 'attendance';
String id = 'id';
String type = 'type';
String latitude = 'latitude';
String longitude = 'longitude';
String time = 'time_stamp';
DataBaseHelper._createInstance();
factory DataBaseHelper() {
if (_dataBaseHelper == null) {
_dataBaseHelper = DataBaseHelper._createInstance();
}
return _dataBaseHelper;
}
Future<Database> get database async{
if (_database == null){
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async{
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'attendance.db';
print(path);
var attendanceDb = await openDatabase(path,version: 1,onCreate: _createDb);
return attendanceDb;
}
// Create Table
void _createDb(Database db,int newVersion) async{
await db.execute('CREATE TABLE $table($id INTEGER PRIMARY KEY AUTOINCREMENT, $type TEXT,$latitude TEXT, $longitude TEXT, $time TEXT)');
}
// Fetch data from DB
Future<List<Map<String, String>>> getDatafromdb() async{
Database db = await this.database;
var result = await db.query(this.table);
return result;
}
// Insert data to DB
Future<int> insertData(DataBase dataBase) async{
var db = await this.database;
print('database');
print(db);
var result = await db.insert(this.table, dataBase.toMap());
return result;
}
// Delete data from DB
Future<int> deleteData(int Id) async{
var db = await this.database;
var result = await db.rawDelete('DELETE FROM $table WHERE $id = $Id');
return result;
}
}
the error
An Observatory debugger and profiler on CPH1853 is available at:
http://127.0.0.1:43427/vxgmPQJhR4E=/
For a more detailed help message, press "h". To detach, press "d"; to quit,
press "q".
I/flutter (27382): createDataBaseObj
I/flutter (27382): {type: IN, latitude: 11.1115482, longitude: 77.3637584, timeStamp: 12:09:29 Thu 2 Jan}
E/flutter (27382): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'insertData' was called on null.
E/flutter (27382): Receiver: null
E/flutter (27382): Tried calling: insertData(Instance of 'DataBase')
E/flutter (27382): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (27382): #1 _MyHomePageState._insertToDb (package:attendance_app/screens/homepage.dart:147:30)
E/flutter (27382): #2 _MyHomePageState.build.<anonymous closure> (package:attendance_app/screens/homepage.dart:58:23)
E/flutter (27382): #3 _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:45:6)
E/flutter (27382): #4 _MyHomePageState.build.<anonymous closure> (package:attendance_app/screens/homepage.dart:55:32)
E/flutter (27382): #5 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (27382): #6 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (27382): #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (27382): #8 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (27382): #9 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (27382): #10 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (27382): #11 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (27382): #12 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (27382): #13 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (27382): #14 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (27382): #15 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (27382): #16 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (27382): #17 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (27382): #18 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (27382): #19 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (27382): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (27382): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (27382): #22 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (27382): #23 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (27382): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (27382): #25 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (27382): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (27382):
I/flutter (27382): Lat: 11.1115482, Long: 77.3637584
Application finished.
You probably need to initialize DataBaseHelper in MyHomePage.
helper = DataBaseHelper();
Related
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
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');
}
},
),
),
);
}
}
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
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.
I'm working on an android app and I'm trying to plugin-like feature which would allow loading additional dex files to extend app functionality. I've figured out how to load additional dex files extending PathClassLoader with few small changes to allow other modules to communicate. The issue is that when the dex files are loaded into the app for the first time when the app is running all works perfectly, then if I decide to disable this module so the classloader is unloaded the app continues to work properly for a few seconds then it throws exception (still continue working properly) and then again few seconds/minutes later (sometimes it takes even 5 minutes) the app crashes with native stack trace. If I decide to load the module which I disabled previously again it will only increase a chance to crash.
This is what happens few seconds module classloader is unloaded:
12-27 01:57:10.839 E/System: Uncaught exception thrown by finalizer
12-27 01:57:10.840 E/System: java.lang.AssertionError: Failed to close dex file in finalizer.
at dalvik.system.DexFile.finalize(DexFile.java:336)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:250)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:237)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)
12-27 01:57:10.840 E/System: Uncaught exception thrown by finalizer
12-27 01:57:10.840 E/System: java.lang.AssertionError: Failed to close dex file in finalizer.
at dalvik.system.DexFile.finalize(DexFile.java:336)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:250)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:237)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)
12-27 01:57:10.841 E/System: Uncaught exception thrown by finalizer
12-27 01:57:10.841 E/System: java.lang.AssertionError: Failed to close dex file in finalizer.
at dalvik.system.DexFile.finalize(DexFile.java:336)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:250)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:237)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)
Then few seconds or minutes later there is native crash:
12-27 01:57:15.409 A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
12-27 01:57:15.409 A/DEBUG: Build fingerprint: 'Sony/G8341/G8341:8.0.0/47.1.A.8.49/3744219090:user/release-keys'
12-27 01:57:15.409 A/DEBUG: Revision: '0'
12-27 01:57:15.409 A/DEBUG: ABI: 'arm64'
12-27 01:57:15.409 A/DEBUG: pid: 17551, tid: 17697, name: Profile Saver >>> com.rowl.plugdj
12-27 01:57:15.409 A/DEBUG: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x657a6983
12-27 01:57:15.409 A/DEBUG: x0 00000000657a6973 x1 0000007bb0739460 x2 0000007bb0600000 x3 0000000000000002
12-27 01:57:15.409 A/DEBUG: x4 0000000000000139 x5 0000007bb073947f x6 2f6d65747379732f x7 726f77656d617266
12-27 01:57:15.409 A/DEBUG: x8 0000000013954588 x9 aec629c3012f5dc2 x10 0000000000000139 x11 000000000000004c
12-27 01:57:15.409 A/DEBUG: x12 656d6172662f6b72 x13 72616a2e6b726f77 x14 000000000000000d x15 aaaaaaaaaaaaaaab
12-27 01:57:15.409 A/DEBUG: x16 0000007bca457cc8 x17 0000007bca3f5f60 x18 0000007bc9c07eb0 x19 0000007baecba270
12-27 01:57:15.409 A/DEBUG: x20 0000007ba6ab68c0 x21 0000007baecba588 x22 0000007ba6ab4298 x23 0000007baa692b18
12-27 01:57:15.409 A/DEBUG: x24 0000000000000000 x25 0000000000002710 x26 00000000977434b0 x27 0000000097746934
12-27 01:57:15.409 A/DEBUG: x28 0000007bc99b6b70 x29 0000007baecba1d0 x30 0000007bc96cf67c
12-27 01:57:15.409 A/DEBUG: sp 0000007baecba0c0 pc 0000007bc96cf634 pstate 0000000080000000
12-27 01:57:15.411 A/DEBUG: backtrace:
12-27 01:57:15.411 A/DEBUG: #00 pc 00000000002fe634 /system/lib64/libart.so (_ZN3art3jit12JitCodeCache18GetProfiledMethodsERKNSt3__13setINS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS2_4lessIS9_EENS7_IS9_EEEERNS2_6vectorINS_17ProfileMethodInfoENS7_ISH_EEEE+228)
12-27 01:57:15.411 A/DEBUG: #01 pc 000000000030ac08 /system/lib64/libart.so (_ZN3art12ProfileSaver20ProcessProfilingInfoEbPt+1452)
12-27 01:57:15.411 A/DEBUG: #02 pc 00000000003099ac /system/lib64/libart.so (_ZN3art12ProfileSaver3RunEv+704)
12-27 01:57:15.411 A/DEBUG: #03 pc 000000000030b7b8 /system/lib64/libart.so (_ZN3art12ProfileSaver21RunProfileSaverThreadEPv+88)
12-27 01:57:15.411 A/DEBUG: #04 pc 00000000000667d0 /system/lib64/libc.so (_ZL15__pthread_startPv+36)
12-27 01:57:15.411 A/DEBUG: #05 pc 000000000001f2a4 /system/lib64/libc.so (__start_thread+68)
Here is the classloader which I'm using
public class ExtensionClassLoader extends PathClassLoader {
private final Map<String, Class<?>> classes = new HashMap();
private final ExtensionManager extensionManager;
public ExtensionClassLoader(ExtensionManager extensionManager, String dexPath, String librarySearchPath, ClassLoader parent) {
super(dexPath, librarySearchPath, parent);
this.extensionManager = extensionManager;
}
#Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.startsWith("com.rowl.") || name.startsWith("dj.plug.")) {
throw new ClassNotFoundException(name);
}
PlugDJ.d("Find Class: " + name);
Class clazz = classes.get(name);
if(clazz == null){
clazz = extensionManager.getClass(name);
if(clazz == null){
clazz = super.findClass(name);
if(clazz != null){
extensionManager.addClass(name, clazz);
}
}
if(clazz != null){
classes.put(name, clazz);
}
}
return clazz;
}
#Override
public String findLibrary(String name) {
return super.findLibrary(name);
}
public Set<String> getClasses(){
return classes.keySet();
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
}
Additionally here is the class which loads these modules:
class ExtensionManager(plugDJInstance: PlugDJ) : Manager(plugDJInstance) {
private val classes = HashMap<String, Class<*>>()
private val extensionLoaders = HashMap<String, ExtensionClassLoader>()
private val loadedExtensions = ArrayList<PDJExtension>()
private val availableExtensions = ArrayList<PDJExtensionInfo>()
val plugAPI = PlugAPIImpl(pdjInstance as PlugDJAndroid)
private val context by lazy { (pdjInstance as PlugDJAndroid).context }
private val extensionSettings by lazy { context.getSharedPreferences("ext", Context.MODE_PRIVATE)}
private val whitelistedExtensions by lazy { extensionSettings.getStringSet("whitelistedExtensions", HashSet<String>()) }
fun addClass(name: String, clazz: Class<*>){
if(!classes.containsKey(name)){
classes.put(name, clazz)
}
}
fun removeClass(name: String){
classes.remove(name)
}
fun getClass(name: String): Class<*>?{
return classes[name]
}
private fun loadApk(dir: File, dexOutputDir: File, parent: ClassLoader): ExtensionClassLoader{
val files = StringBuilder()
dir.listFiles().filter { it.extension == "apk" }.forEach {
files.append(it.absolutePath).append(":")
}
files.deleteCharAt(files.length - 1)
return ExtensionClassLoader(this, files.toString(), dexOutputDir.absolutePath.toString(), parent)
}
fun isExtensionWhitelisted(extInfo: PDJExtensionInfo): Boolean{
return whitelistedExtensions.contains(extInfo.appPackage)
}
#SuppressLint("ApplySharedPref")
fun addExtensionToWhitelist(extInfo: PDJExtensionInfo){
whitelistedExtensions.add(extInfo.appPackage)
extensionSettings.edit().putStringSet("whitelistedExtensions", whitelistedExtensions).commit()
d("Added " + extInfo.appPackage + " to whitelist")
}
#SuppressLint("ApplySharedPref")
fun removeExtensionFromWhitelist(extInfo: PDJExtensionInfo){
whitelistedExtensions.remove(extInfo.appPackage)
extensionSettings.edit().putStringSet("whitelistedExtensions", if(whitelistedExtensions.isEmpty()) null else whitelistedExtensions).commit()
d("Checking... " + whitelistedExtensions)
d("Removed " + extInfo.appPackage + " from whitelist")
}
fun discoverExtensions() {
try{
whitelistedExtensions.forEach {
d("Whitelisted extension: $it")
}
val installedApps = context.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
for(app in installedApps){
if(app.sourceDir.contains("system")) continue
if(app.metaData != null && app.metaData.containsKey("pdjExtensionName")){
val extName = app.metaData.getString("pdjExtensionName")
val extMainClass = app.metaData.getString("pdjExtensionMainClass")
val sourceDir = File(app.sourceDir).parentFile
PlugDJ.i("Found extension: " + extName)
var extInfo = getAvailableExtensions().find { it.appPackage == app.packageName }
d(extInfo?.sourceDirectory.toString() )
d(sourceDir.toString() )
if(extInfo != null){
PlugDJ.d("Removing " + app.packageName)
availableExtensions.remove(extInfo)
}
extInfo = PDJExtensionInfoImpl(extName, sourceDir, app.packageName, extMainClass, "", "", null, null)
availableExtensions.add(extInfo)
}
}
}catch (e: Exception){
e.printStackTrace()
}
}
fun getAvailableExtensions(): List<PDJExtensionInfo>{
return Collections.unmodifiableList(ArrayList(availableExtensions))
}
fun getLoadedExtensions(): List<PDJExtension>{
return Collections.unmodifiableList(ArrayList(loadedExtensions))
}
fun loadExtension(extInfo: PDJExtensionInfo): PDJExtension{
var cl = context.classLoader
val dexOutputDir = context.getDir("dex", Context.MODE_PRIVATE)
val extcl = loadApk(extInfo.sourceDirectory, dexOutputDir, cl)
extensionLoaders[extInfo.name] = extcl
val mainClass = extcl.loadClass(extInfo.mainClass)
val apiField = mainClass.superclass.getDeclaredField("api")
val clField = mainClass.superclass.getDeclaredField("classLoader")
val extField = mainClass.superclass.getDeclaredField("extensionInfo")
val extension = mainClass.newInstance() as PDJExtension
apiField.apply {
isAccessible = true
set(extension, plugAPI)
isAccessible = false
}
clField.apply {
isAccessible = true
set(extension, mainClass.classLoader)
isAccessible = false
}
extField.apply {
isAccessible = true
set(extension, extInfo)
isAccessible = false
}
loadedExtensions.add(extension)
return extension
}
fun getLoadedExtension(appPackage: String): PDJExtension? {
return getLoadedExtensions().find { it.extensionInfo.appPackage == appPackage }
}
fun enableExtension(ext: PDJExtension){
ext.onEnable()
ext::class.java.superclass.getDeclaredField("isEnabled").apply {
isAccessible = true
set(ext, true)
isAccessible = false
}
}
fun disableExtension(ext: PDJExtension){
try{
plugAPI.removeEventListeners(ext)
ext.onDisable()
}catch (e: Exception){
e.printStackTrace()
}
ext::class.java.superclass.getDeclaredField("isEnabled").apply {
isAccessible = true
set(ext, false)
isAccessible = false
}
}
fun unloadExtension(ext: PDJExtension){
d("Unloading extension...")
ext::class.java.superclass.getDeclaredField("api").apply {
isAccessible = true
set(ext, null)
isAccessible = false
}
val cl = ext.classLoader as ExtensionClassLoader
loadedExtensions.remove(ext)
for(className in cl.classes){
removeClass(className)
}
extensionLoaders.remove(ext.extensionInfo.name)
d("Extension unloaded.")
System.runFinalization()
System.gc()
}
}
Additionally, here is the full log https://pastebin.com/Jhpk4Wpc
Any idea what causes it?
Make sure you are not deleting the dex file.