I'm using Flutter stripe_checkout: ^1.0.0 and saw some odd behaviour.
When the checkout button is clicked just once, the screen would turn blank with the following printout. On Stripe dashboard, it says, "Incomplete - The customer has not entered their payment method'.
I/flutter (32631): Checkout session id cs_test_a10k5Lsopaz9JupfebE9pW77ZgUpucfzCrh1WTKX9KcApdbKztnZiz1SKe
I/WebViewFactory(32631): Loading com.google.android.webview version 83.0.4103.106 (code 410410681)
I/cr_VariationsUtils(32631): Requesting new seed from IVariationsSeedServer
I/cr_LibraryLoader(32631): Loaded native library version number "83.0.4103.106"
I/cr_CachingUmaRecorder(32631): Flushed 3 samples from 3 histograms.
I/TetheringManager(32631): registerTetheringEventCallback:com.healthcare.jaaba
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
W/GooglePlayServicesUtil(32631): Google Play Store is missing.
E/cr_PlatformSer-Internal(32631): UsageReporting query failed
W/ealthcare.jaab(32631): Accessing hidden method Landroid/media/AudioManager;->getOutputLatency(I)I (greylist, reflection, allowed)
D/HostConnection(32631): HostConnection::get() New Host Connection established 0xf4e7e280, tid 752
E/cr_PlatformSer-Internal(32631): Unable to determine Safe Browsing user opt-in preference
D/HostConnection(32631): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
D/EGL_emulation(32631): eglCreateContext: 0xf4e7c140: maj 3 min 0 rcv 3
D/EGL_emulation(32631): eglMakeCurrent: 0xf4e7c140: ver 3 0 (tinfo 0xaf33b210) (first time)
D/EGL_emulation(32631): eglMakeCurrent: 0xf4e60d10: ver 3 0 (tinfo 0xf51b1d50) (first time)
W/Gralloc4(32631): allocator 3.x is not supported
I/VideoCapabilities(32631): Unsupported profile 4 for video/mp4v-es
W/cr_MediaCodecUtil(32631): HW encoder for video/avc is not available on this device.
D/EGL_emulation(32631): eglCreateContext: 0xf4e7f1d0: maj 3 min 0 rcv 3
I/ealthcare.jaab(32631): NativeAlloc concurrent copying GC freed 50165(3378KB) AllocSpace objects, 15(428KB) LOS objects, 49% free, 3769KB/7539KB, paused 2.245ms total 147.024ms
W/ealthcare.jaab(32631): Reducing the number of considered missed Gc histogram windows from 124 to 100
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
However, when the checkout button is clicked 3 - 5 times continuously, the card form appears and the payment would be successful.
I/flutter (32631): Checkout session id cs_test_a1ZwZrvL4812TEpjFwQ649RMYjirJr9TMwQVZ29JYrjGj54gmqkCtTyfTW
I/flutter (32631): Checkout session id cs_test_a13D23W9EY1SgLBqYIZLAHTvFBcHKY1wUIiZdr3Kb6XPNsrrLEfj3KJjkj
I/ealthcare.jaab(32631): NativeAlloc concurrent copying GC freed 7125(419KB) AllocSpace objects, 0(0B) LOS objects, 49% free, 3431KB/6863KB, paused 1.352ms total 189.441ms
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/flutter (32631): Checkout session id cs_test_a1QsxT2t7H68MpvgLinDukwOBzwW1W21ktnbQdqB25R6t2b0TE5mO4u9jj
I/flutter (32631): Checkout session id cs_test_a1o2VPwBSq0RRW6PlSKnGr554hoWFIOrPy1NZWnLveMqAZyLX6iVYKFr0y
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/flutter (32631): Checkout session id cs_test_a1uWleO9v9VAwUAra957z8uHbpOwNyp24nZYgAQ2aOLHqwt3hBcOtAg8Yf
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1)
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/fingerprinted/js/stripe-a07f9e62b0b55658b30abedf1005cae0.js (1)
I/chatty (32631): uid=10139(com.healthcare.jaaba) identical 1 line
I/chromium(32631): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/fingerprinted/js/stripe-a07f9e62b0b55658b30abedf1005cae0.js (1)
I/Choreographer(32631): Skipped 31 frames! The application may be doing too much work on its main thread.
I/chromium(32631): [INFO:CONSOLE(265)] "Uncaught ReferenceError: PaymentRequest is not defined", source: https://pay.google.com/gp/p/js/pay.js (265)
Flutter Application: checkout_screen.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:stripe_checkout/stripe_checkout.dart';
import 'package:flutter/material.dart';
import '../../../../utils/env.dart';
import '../widgets/example_scaffold.dart';
import '../../../../utils/api_endpoints.dart';
import 'platforms/stripe_checkout.dart' if (dart.library.js)
'platforms/stripe_checkout_web.dart';
class CheckoutScreenExample extends StatefulWidget {
const CheckoutScreenExample({Key? key}) : super(key: key);
#override
_CheckoutScreenExample createState() => _CheckoutScreenExample();
}
class _CheckoutScreenExample extends State<CheckoutScreenExample> {
#override
Widget build(BuildContext context) {
return ExampleScaffold(
title: 'Checkout Page',
padding: const EdgeInsets.all(16),
children: [
const SizedBox(height: 120),
Center(
child: ElevatedButton(
onPressed: checkout,
child: const Text('Open Checkout'),
),
)
],
);
}
Future<void> checkout() async {
final String sessionId = await _createCheckoutSession();
final result = await redirectToCheckout(
context: context,
sessionId: sessionId,
publishableKey: stripePublishableKey,
successUrl: 'https://checkout.stripe.dev/success',
canceledUrl: 'https://checkout.stripe.dev/cancel',
);
if (mounted) {
final text = result.when(
success: () => 'Paid successfully',
canceled: () => 'Checkout canceled',
error: (e) => 'Error $e',
redirected: () => 'Redirected successfully',
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(text)),
);
}
}
Future<String> _createCheckoutSession() async {
final stripePayURL = Uri.parse(ApiUrl.stripePayUrl);
final response = await http.get(
stripePayURL,
headers: <String, String>{'Authorization': 'Bearer ' + token,
},
);
final Map<String, dynamic> bodyResponse = json.decode(response.body);
final id = bodyResponse['checkout_session_id'] as String;
debugPrint('Checkout session id $id');
return id;
}
}
Flask Backend: billing.py
#api_blueprint.route('/stripe_pay', methods=['GET'])
#token_auth.login_required
def stripe_pay():
cart_id = basic_auth.current_user().id
transaction = Transaction.query.filter(Transaction.cart_id==cart_id).first()
price = stripe.Price.create(
unit_amount=transaction.count_grand_total(),
currency=transaction.currency,
)
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price': price,
'quantity': 1,
}],
mode='payment',
success_url=url_for('api.success', cart_id=cart_id, _external=True) + '?cart_id=cart_id' + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=url_for('home.index', _external=True),
)
return jsonify ({
'checkout_session_id': session['id'],
'checkout_public_key': checkout_public_key,
'cart_id': int(cart_id)
})
I would appreciate if someone show me how to fix this. Thank you.
Related
iam make a button to google map activity. everytime i click my apps just freeze and show many log. iam already set api key in manifest. i add google_maps_flutter: ^2.0.2 to pubspec.yaml. and every time i click the button looks like the request count in google consule. i dont know where must to fix.
this is the maps activity
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class Maps extends StatefulWidget {
const Maps({Key? key}) : super(key: key);
#override
State<Maps> createState() => _MapsState();
}
class _MapsState extends State<Maps> {
static const _initialCameraPosition = CameraPosition(
target: LatLng(-8.69407, 115.21146),
zoom: 11.5);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Center(child: Text('Google Map')),elevation: 10,),
body: SafeArea(
child: GoogleMap(
mapToolbarEnabled: false,
initialCameraPosition: _initialCameraPosition,
),
),
);
}
}
this is the log
[GETX] GOING TO ROUTE /Maps
D/MapsInitializer( 3931): preferredRenderer: null
D/zzca ( 3931): preferredRenderer: null
I/zzca ( 3931): Making Creator dynamically
I/DynamiteModule( 3931): Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:203112999
I/DynamiteModule( 3931): Selected remote version of com.google.android.gms.maps_dynamite, version >= 203112999
V/DynamiteModule( 3931): Dynamite loader version >= 2, using loadModule2NoCrashUtils
I/PGA ( 3931): hstInit: opened /dev/bstpgaipc: fd = 70
I/PGA ( 3931): Attempting to create new SOCKET connection pid = 3931, tid = 3949
I/PGA ( 3931): hstInitClientPgaIpc: Attempting to get GROUP2 cid
I/PGA ( 3931): hstInitClientPgaIpc: data mapped to 0x9a71a000 with size 4194304
I/PGA ( 3931): New SOCKET connection: com.example.gym (pid 3931, tid 3949)
I/PGA ( 3931): hstInit: opened /dev/bstpgaipc: fd = 73
I/PGA ( 3931): Attempting to create new SOCKET connection pid = 3931, tid = 3950
I/PGA ( 3931): hstInitClientPgaIpc: Attempting to get GROUP2 cid
I/PGA ( 3931): hstInitClientPgaIpc: data mapped to 0x99b4e000 with size 4194304
I/PGA ( 3931): New SOCKET connection: com.example.gym (pid 3931, tid 3950)
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000006/n/x86
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000006/n/armeabi-v7a
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000006/n/armeabi
I/Google Maps Android API( 3931): Google Play services client version: 12451000
D/MapsInitializer( 3931): loadedRenderer: LEGACY
D/zzca ( 3931): preferredRenderer: null
I/Google Maps Android API( 3931): Google Play services package version: 203615022
D/TelephonyManager( 3931): creating subscriptionInfo Record, context : android.app.Application#19dab52
D/NetworkSecurityConfig( 3931): No Network Security Config specified, using platform default
E/GoogleMapController( 3931): Cannot enable MyLocation layer as location permissions are not granted
I/PGA ( 3931): hstInit: opened /dev/bstpgaipc: fd = 102
I/PGA ( 3931): Attempting to create new SOCKET connection pid = 3931, tid = 4140
I/PGA ( 3931): hstInitClientPgaIpc: Attempting to get GROUP2 cid
I/PGA ( 3931): hstInitClientPgaIpc: data mapped to 0x96fb6000 with size 4194304
I/PGA ( 3931): New SOCKET connection: com.example.gym (pid 3931, tid 4140)
W/DynamiteModule( 3931): Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule( 3931): Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:6
I/DynamiteModule( 3931): Selected remote version of com.google.android.gms.googlecertificates, version >= 6
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000005/n/x86
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000005/n/armeabi-v7a
W/System ( 3931): ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000005/n/armeabi
I'm trying to run an integration test which is highly dependent on the user clicking a magic link he got in his email. So far I failed to find a way of doing that. I came across Process.run but it seems like it should be run before the integration test starts and I need to do it during the test.
Any help with either iOS or Android will be highly appreciated. 🙏
This is the code I tried so far to work on iOS but Process.run ends with ProcessException: No such file or directory:
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('login test', (WidgetTester tester) async {
app_sandbox.main();
await tester.pumpAndSettle(Duration(seconds: 5));
expect(find.text('foo'), findsOneWidget);
await Process.run('xcrun', [
'simctl',
'openurl',
'7D6DEC47-C1E2-4F18-A38B-7B4C17558172',
'https://myDeepLink/sign-in',
]);
await tester.pumpAndSettle();
});
}
this might only work with flutter_driver
await Process.run('xcrun', [
'simctl',
'openurl',
'booted',
'https://myDeepLink/sign-in'
]).then((result) {
stdout.write(result.stdout);
stderr.write(result.stderr);
});
not with testWidgets of integration_test
there I got this error:
> Error occured: DriverError: Failed to fulfill RequestData due to
> remote error Original error: ext.flutter.driver: (112) Service has
> disappeared Original stack trace:
> #0 new _OutstandingRequest (package:vm_service/src/vm_service.dart:1746:45)
> #1 VmService._call (package:vm_service/src/vm_service.dart:2262:21)
> #2 VmService.callServiceExtension (package:vm_service/src/vm_service.dart:2233:14)
> #3 VMServiceFlutterDriver.sendCommand (package:flutter_driver/src/driver/vmservice_driver.dart:306:66)
> #4 FlutterDriver.requestData (package:flutter_driver/src/driver/driver.dart:522:45)
> #5 integrationDriver (package:integration_test/integration_test_driver_extended.dart:51:38)
> <asynchronous suspension>
I have a miniplayer where I have a video widget (I use better_player which depends on chewie and video_player). Everything works great unless I want to dismiss the miniplayer. The video is replaced with a black screen. I did some debugging and found out that for some reason the dispose() method is called on my video_widget twice (when I start dismissing and when I end dismissing my miniplayer). Below is a video that shows this behavior:
Could you help me with fixing this issue?
EDIT
I did some more debugging and found out that it is probably related to the video widget or better_player package. Also, I found out that when using chewie behavior is nearly the same but with chewie when I start dismissing video gets black for a millisecond and then initializes again and starts playing from the beginning. Here is the code of my `video widget class.
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/services.dart';
import 'package:cook_it/screens/longs_page/providers/providers.dart';
import 'package:path_provider/path_provider.dart';
import 'package:better_player/better_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class LongsVideoItem extends StatefulWidget {
const LongsVideoItem({Key? key }) : super(key: key);
#override
_LongsVideoItemState createState() => _LongsVideoItemState();
}
class _LongsVideoItemState extends State<LongsVideoItem> {
void _toggleVideoControls(bool show){
if (show){
_betterPlayerController.setControlsEnabled(true);
}else{
_betterPlayerController.setControlsEnabled(false);
}
}
Future _saveAssetVideoToFile() async {
final content = await rootBundle.load("assets/videos/second.mp4");
final directory = await getApplicationDocumentsDirectory();
final file = File("${directory.path}/second.mp4");
_directory = "${directory.path}/second.mp4";
file.writeAsBytesSync(content.buffer.asUint8List());
}
BetterPlayerController _betterPlayerController = BetterPlayerController(const BetterPlayerConfiguration());
dynamic _directory;
#override
void initState() {
_saveAssetVideoToFile().then((value) {
final BetterPlayerDataSource betterPlayerDataSource = BetterPlayerDataSource(
BetterPlayerDataSourceType.file,
_directory.toString(),
);
_betterPlayerController = BetterPlayerController(
const BetterPlayerConfiguration(
deviceOrientationsAfterFullScreen: [DeviceOrientation.portraitUp],
aspectRatio: 16/9,
autoPlay: true,
controlsConfiguration: BetterPlayerControlsConfiguration(showControlsOnInitialize: false),
),
betterPlayerDataSource: betterPlayerDataSource,
);
});
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, _){
if (watch(videoShowControlsProvider).state == true){
_toggleVideoControls(true);
}else if (watch(videoShowControlsProvider).state == false){
_toggleVideoControls(false);
}
return BetterPlayer(controller: _betterPlayerController,);
}
);
}
}
here are the logs when I start dismissing
I/ExoPlayerImpl(16667): Release cd87770 [ExoPlayerLib/2.14.1] [HWCLT, CLT-L29, HUAWEI, 28] [goog.exo.core]
W/ACodec (16667): forcing OMX state to Idle when received shutdown in ExecutingState
3
E/BufferQueueProducer(16667): [SurfaceTexture-0-16667-145] cancelBuffer: BufferQueue has been abandoned
I/chatty (16667): uid=10234(com.example.cook_it) JNISurfaceTextu identical 10 lines
E/BufferQueueProducer(16667): [SurfaceTexture-0-16667-145] cancelBuffer: BufferQueue has been abandoned
D/SurfaceUtils(16667): disconnecting from surface 0x797bec7010, reason disconnectFromSurface
I/ExoPlayerImpl(16667): Init 8b84e21 [ExoPlayerLib/2.14.1] [HWCLT, CLT-L29, HUAWEI, 28]
V/AudioManager(16667): getStreamVolume treamType: 3
V/AudioManager(16667): isStreamMute streamType: 3
V/AudioManager(16667): getStreamMaxVolume treamType: 3
E/ (16667): [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
I/OMXClient(16667): IOmx service obtained
I/ACodec (16667): In onAllocateComponent create compenent, codec name: OMX.hisi.video.decoder.avc
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason connectToSurface
I/MediaCodec(16667): [OMX.hisi.video.decoder.avc] setting surface generation to 17067154
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason connectToSurface(reconnect)
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason connectToSurface(reconnect)
E/ACodec (16667): [OMX.hisi.video.decoder.avc] setPortMode on output to DynamicANWBuffer failed w/ err -2147483648
I/HwExtendedCodec(16667): mime is [video/avc] at setVideoFormat
I/ACodec (16667): codec does not support config priority (err -22)
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
I/ACodec (16667): onStart
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): set up nativeWindow 0x797c027010 for 1920x1080, color 0x30d, rotation 0, usage 0x20002900
6
W/MapperHal(16667): buffer descriptor with invalid usage bits 0x2000
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
2
I/ACodec (16667): [OMX.hisi.video.decoder.avc] got color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) err=0(NO_ERROR)
I/ACodec (16667): [OMX.hisi.video.decoder.avc] using color aspects (R:2(Limited), P:1(BT709_5), M:1(BT709_5), T:3(SMPTE170M)) and dataspace 0x104
D/SurfaceUtils(16667): disconnecting from surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): connecting to surface 0x797c027010, reason setNativeWindowSizeFormatAndUsage
D/SurfaceUtils(16667): set up nativeWindow 0x797c027010 for 1920x1088, color 0x30d, rotation 0, usage 0x20002900
W/ACodec (16667): [OMX.hisi.video.decoder.avc] setting nBufferCountActual to 19 failed: -2147483648
18
W/MapperHal(16667): buffer descriptor with invalid usage bits 0x2000
I/ACodec (16667): date space update : 0x104
I believe that for some reason this widget calls the dispose() method when I start dismissing. But why is that happening and how can I prevent that from happening?
I found the answer. The problem was in the miniplayer package. In case someone has the same problem comment here and I will explain how to fix it.
I'm using socket_io_client v0.9.12 in my flutter app (still not using null safety). I am creating a socket connection with my back-end server when the app starts and allow child widgets to access it using a provider.
I am trying to start creating the connection in the constructor so that when I need to use the socket client, it would probably be initialized already.
This is my provider class which has the creation of the socket connection:
class SocketClient {
SocketClient() {
_initializer = initialize();
}
Future _initializer;
/// Socket client
Socket client;
/// Wait until the client is properly connected with the server
Future finishInitializing() => _initializer;
/// Initialize the socket connection with the server
Future initialize() async {
final completer = Completer<Socket>();
final socket = io(
'http://localhost:3000/gateway',
OptionBuilder() //
.setTransports(['websocket'])
.disableAutoConnect()
.setQuery({'token': 'TOKEN'})
.build(),
)..connect();
socket
..onConnect((_) {
completer.complete(socket);
});
client = await completer.future;
}
}
The main app widget I have:
#override
Widget build(BuildContext context) {
return Provider<SocketClient>(
create: (_) => SocketClient(),
builder: (context, _) {
return Scaffold(
...
);
},
);
}
This is how I am trying to use the socket client:
Future<void> foo(SocketClient socketClient) async {
await socketClient.finishInitializing();
final socket = socketClient.client;
socket.on(eventName, (dynamic uploadDrawingEvent) {
...
});
}
Everything works fine up to now. 🎉
However, when I try to run my tests that depend on this socket client, I see the below error:
Pending timers:
Timer (duration: 0:00:20.000000, periodic: false), created:
#0 new FakeTimer._ (package:fake_async/fake_async.dart:284:41)
#1 FakeAsync._createTimer (package:fake_async/fake_async.dart:248:27)
#2 FakeAsync.run.<anonymous closure> (package:fake_async/fake_async.dart:181:19)
#5 Manager.connect (package:socket_io_client/src/manager.dart:232:19)
#6 Manager.open (package:socket_io_client/src/manager.dart:194:41)
#7 Socket.connect (package:socket_io_client/src/socket.dart:104:8)
#8 SocketClient.initialize (package:flutter_app/web/services/socket_provider.dart:48:8)
<asynchronous suspension>
(elided 2 frames from dart:async)
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1241 pos 12: '!timersPending'
When the exception was thrown, this was the stack:
#2 AutomatedTestWidgetsFlutterBinding._verifyInvariants (package:flutter_test/src/binding.dart:1241:12)
#3 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:803:7)
<asynchronous suspension>
(elided 2 frames from class _AssertionError)
...
initialize function keeps hanging after client = await completer.future; line. That future is not resolved even after the test is finished (see the error).
I would like to get ideas on how I can mock this socket client properly to avoid this error.
I'm looking more towards an answer which mocks the functionality of the socket client because I have some more tests to write to cover the event handlers.
Thank you in advance! 🙏
You can use await IOOverrides for override standard Socket method like socketConnect
Exemple:
await IOOverrides.runZoned(() async {
your code
}, socketConnect: (host, port, {sourceAddress, int sourcePort = 0, timeout}) => Future.value(mockSocket));
I am using Flutter contact picker 0.0.2. But it is giving some weird error. It shows the contact list when I call selectContact Future, however, after selecting a particular contact from the list, the app crashes, and it gives me the below-mentioned error on console.
I have also tried with adding permission in android, even though it is not required, still, it does not work.
Code :
class _MobileNumberWidgetState extends State<MobileNumberWidget> {
final TextEditingController _phoneNumberController = TextEditingController();
final ContactPicker _contactPicker = new ContactPicker();
Contact _contact;
#override
Widget build(BuildContext context) {
return AppWidgets.shadowContainerComplete(
child:Row(
children: <Widget>[
Expanded(
child: TextField(
controller: _phoneNumberController,
decoration: AppStyles.textField(hint: "Enter Phone Number", iconData: Icons.phone_iphone),
),
),
IconButton(
icon: Icon(Icons.format_list_numbered),
onPressed: () async{
Contact contact = await _contactPicker.selectContact();
setState(() {
_contact = contact;
});
},
)
],
)
);
}
}
Console :
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
D/FlutterActivity(17398): Using the launch theme as normal theme.
D/FlutterActivityAndFragmentDelegate(17398): Setting up FlutterEngine.
D/FlutterActivityAndFragmentDelegate(17398): No preferred FlutterEngine was provided. Creating a new FlutterEngine for this FlutterFragment.
D/FlutterActivityAndFragmentDelegate(17398): Attaching FlutterEngine to the Activity that owns this Fragment.
D/FlutterView(17398): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine#43c3a74
D/FlutterActivityAndFragmentDelegate(17398): Executing Dart entrypoint: main, and sending initial route: /
Debug service listening on ws://127.0.0.1:28145/jPIcHt_yF9E=/ws
Syncing files to device Android SDK built for x86...
D/EGL_emulation(17398): eglMakeCurrent: 0xe121a6c0: ver 3 1 (tinfo 0xe120f8a0)
D/eglCodecCommon(17398): setVertexArrayObject: set vao to 0 (0) 1 0
D/EGL_emulation(17398): eglMakeCurrent: 0xe121a180: ver 3 1 (tinfo 0xe120fa70)
D/FlutterView(17398): Detaching from a FlutterEngine: io.flutter.embedding.engine.FlutterEngine#43c3a74
D/AndroidRuntime(17398): Shutting down VM
E/AndroidRuntime(17398): FATAL EXCEPTION: main
E/AndroidRuntime(17398): Process: maaz.easyapproach.kashbak, PID: 17398
E/AndroidRuntime(17398): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2015, result=-1, data=Intent { dat=content://com.android.contacts/data/1 flg=0x1 }} to activity {maaz.easyapproach.kashbak/maaz.easyapproach.kashbak.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.app.Activity.getContentResolver()' on a null object reference
E/AndroidRuntime(17398): at android.app.ActivityThread.deliverResults(ActivityThread.java:4845)
E/AndroidRuntime(17398): at android.app.ActivityThread.handleSendResult(ActivityThread.java:4886)
E/AndroidRuntime(17398): at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
E/AndroidRuntime(17398): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime(17398): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime(17398): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
E/AndroidRuntime(17398): at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(17398): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(17398): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/AndroidRuntime(17398): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(17398): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/AndroidRuntime(17398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/AndroidRuntime(17398): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.app.Activity.getContentResolver()' on a null object reference
E/AndroidRuntime(17398): at net.goderbauer.flutter.contactpicker.ContactPickerPlugin.onActivityResult(ContactPickerPlugin.java:68)
E/AndroidRuntime(17398): at io.flutter.embedding.engine.FlutterEnginePluginRegistry$FlutterEngineActivityPluginBinding.onActivityResult(FlutterEnginePluginRegistry.java:634)
E/AndroidRuntime(17398): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.onActivityResult(FlutterEnginePluginRegistry.java:367)
E/AndroidRuntime(17398): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onActivityResult(FlutterActivityAndFragmentDelegate.java:546)
E/AndroidRuntime(17398): at io.flutter.embedding.android.FlutterActivity.onActivityResult(FlutterActivity.java:594)
E/AndroidRuntime(17398): at android.app.Activity.dispatchActivityResult(Activity.java:8110)
E/AndroidRuntime(17398): at android.app.ActivityThread.deliverResults(ActivityThread.java:4838)
E/AndroidRuntime(17398): ... 11 more
I/Process (17398): Sending signal. PID: 17398 SIG: 9
Lost connection to device.