How to connect to Localhost? - flutter

I'm here new, I'm learning flutter and I need login with this:
POST http://localhost:3000/api/users/session
But I still can't login :( I'm waiting 5 minutes and still there is a loading screen with no effects.
I have try
So I have have made a this api_service with this tutorial made https://www.youtube.com/watch?v=_Kw4BfNX1-4
here is my api_service.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../model/login_model.dart';
class APIService {
Future<LoginResponseModel>
login(LoginRequestModel requestModel) async {
String url = "http://localhost:3000/api/users/session";
final response = await http.post(url, body: requestModel.toJson());
if (response.statusCode == 200 || response.statusCode == 400) {
return LoginResponseModel.fromJson(
json.decode(response.body),
);
} else {
throw Exception('Failed to load data!');
}
}
}
Here is debug console:
E/flutter (10967): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: SocketException: OS Error: Connection refused,
errno = 111, address = localhost, port = 58856 E/flutter (10967):
I'm try with this page:
https://medium.com/#podcoder/connecting-flutter-application-to-localhost-a1022df63130
I change String url = "http://localhost:3000/api/users/session"; to
String url = "http://10.0.2.2:3000/api/users/session";
in my debug console i have completely different messages, but stilll
don't work :(
E/flutter (10967):
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: Bad state: Insecure HTTP is not allowed by
platform: http://10.0.2.2:3000/api/users/session
E/flutter (10967): #0 _HttpClient._openUrl
(dart:_http/http_impl.dart:2434:7)
E/flutter (10967): #1 _HttpClient.openUrl
(dart:_http/http_impl.dart:2341:7)
E/flutter (10967): #2 IOClient.send
package:http/src/io_client.dart:31
(...) to #28 and the last ist E/flutter (10967):

Fix for the Error Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform
Flutter terms http as an insecure source Therefore you should either use https or set android:usesCleartextTraffic to true in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="receipt"
android:usesCleartextTraffic="true" // Add this line
android:icon="#mipmap/ic_launcher">

Related

How to unzip files to device memory in flutter

I was able to download file in zip format from remote server, but when unzip the file containing videos, I got error like this
E/flutter (11680): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Creation failed, path = 'out' (OS Error: Read-only file system, errno = 30)
E/flutter (11680): #0 _Directory.createSync (dart:io/directory_impl.dart:133:7)
E/flutter (11680): #1 extractArchiveToDisk
package:archive/…/io/extract_archive_to_disk.dart:21
E/flutter (11680): #2 ZipService.unzipSigns
package:gsl_distionary/services/zip_service.dart:13
E/flutter (11680): <asynchronous suspension>
Below is my code to unzip file using archive package:
static Future unzipSigns(String fileName) async {
final dir = await getApplicationSupportDirectory();
final bool isZippedFile = await File("${dir.path}/$fileName").exists();
if (isZippedFile) {
final inputStream = InputFileStream("${dir.path}/$fileName");
final archive = ZipDecoder().decodeBuffer(inputStream);
extractArchiveToDisk(archive, 'out');
}
}
What did I miss?

Can't fetch NetworkImage for Flutter from Google Cloud Storage bucket

I want to load a NetworkImage in Flutter but can't get it to work because of a:
Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:393))
Does not work (Image from Google Cloud Storage + Cloud CDN)
NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500")
However this does work (test image from the webz)
NetworkImage("https://picsum.photos/250?image=9")
This is the full error message:
======== Exception caught by image resource service ================================================
The following HandshakeException was thrown resolving an image codec:
Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate(handshake.cc:393))
When the exception was thrown, this was the stack:
#0 _SecureFilterImpl._handshake (dart:io-patch/secure_socket_patch.dart:99:46)
#1 _SecureFilterImpl.handshake (dart:io-patch/secure_socket_patch.dart:142:25)
#2 _RawSecureSocket._secureHandshake (dart:io/secure_socket.dart:911:54)
#3 _RawSecureSocket._tryFilter (dart:io/secure_socket.dart:1040:19)
<asynchronous suspension>
Image provider: NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500", scale: 1.0)
Image key: NetworkImage("https://cdn.vaandra.com/items/f69f662f-41ff-4bb1-bd50-75a70b7ca6a5/439806b1-cacc-4d58-85a5-601bcb825fe3-p-500", scale: 1.0)
====================================================================================================
Although the error claims that this is a certificate problem I can't understand how it does work with that public image that also comes through https?
Create a class that extends the http override
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
And use it in the main function
void main(){
HttpOverrides.global = new MyHttpOverrides();
runApp(MyApp());
}

Flutter socket.io connected but throws error(server node.js)

// please try to help if you can
socketConnect(){
IO.Socket socket = IO.io('https://8476-113-20-17-134.ngrok.io/',
IO.OptionBuilder()
.disableAutoConnect()
.setTransports(['websocket'])
.build()
);
socket.connect();
socket.onConnect((_) {
print('connect');
});
socket.on("testingnirav", (data) => print(data) );
}
Show Connected in Backend Server Log but throws below error in flutter socket_io_client
E/flutter ( 9164): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int'
E/flutter ( 9164): #0 Socket.onHandshake (package:socket_io_client/src/engine/socket.dart:481:5)
E/flutter ( 9164): #1 Socket.onPacket (package:socket_io_client/src/engine/socket.dart:449:11)
// link send me to this location
pingInterval = data['pingInterval'];

Flutter Unhandled Exception: Null check operator used on a null value

I am getting the following error Unhandled Exception: Null check operator and I am not sure if it is something wrong in my code or the library I am using. I am trying to test the livequery of the parse_server_sdk used by back4app because I require sending and receiving images in Realtime. Here is the relevant code:
import 'dart:io';
import 'package:filepicker_windows/filepicker_windows.dart';
import 'package:flutter/material.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
void main() async {
final keyApplicationId = 'EPARW6nRAAyp5uehoDE7rBEby4wtehcZf9EayykS';
final keyClientKey = 'fDaL2DjyC9YdwCwZ4RB5c5vhACROaMOO1EjjL4Zn';
final keyParseServerUrl = 'https://parseapi.back4app.com';
final LIVE_QUERY_URL = 'wss://samuraichat.b4a.io';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey,
autoSendSessionId: true,
liveQueryUrl: LIVE_QUERY_URL,
coreStore: CoreStoreMemoryImp());
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('FirstClass'))
..whereEqualTo('chatId', 1);
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.create, (value) {
print('*** CREATE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).get('message'));
});
runApp(MyApp());
}
Here is the error stack:
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
#0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
#1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
#2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
#3 MethodChannelConnectivity.checkConnectivity (package:connectivity_platform_interface/src/method_channel_connectivity.dart:41:29)
#4 Connectivity.checkConnectivity (package:connectivity/connectivity.dart:46:22)
#5 Parse.checkConnectivity (package:parse_server_sdk_flutter/parse_server_sdk.dart:106:34)
#6 new LiveQueryReconnectingController (package:parse_server_sdk/src/network/parse_live_query.dart:45:28)
#7 new LiveQueryClient._internal (package:parse_server_sdk/src/network/parse_live_query.dart:146:30)
#8 LiveQueryClient._getInstance (package:parse_server_sdk/src/network/parse_live_query.dart:153:35)
#9 new LiveQuery (package:parse_server_sdk/src/network/parse_live_query.dart:416:30)
#10 main (package:chat_app/main.dart:18:37)
<asynchronous suspension>
Thanks.
Try to clean your app cache:
flutter clean
This bug should be fixed with this PR.
You use the current nullsafety branch by overriding the dependency in your pubspec.yaml:
dependency_overrides:
parse_server_sdk_flutter:
git:
url: https://github.com/parse-community/Parse-SDK-Flutter.git
ref: nullsafety
path: packages/flutter
parse_server_sdk:
git:
url: https://github.com/parse-community/Parse-SDK-Flutter.git
ref: nullsafety
path: packages/dart

audio_service flutter package does not start

I am trying to use the audio_service package to allow background controls for my podcast playing app. The service does not start. When I call AudioService.start(), nothing is ever returned (I'm awaiting this function and trying to print a statement after this returns, but it never returns. Also, when I first attempt to play an item, it will correctly evaluate AudioService.running to false and then try to start the AudioService (hanging on the start() function). When I hit play a second time, it will evaluate AudioService.running as true (even though the start function never returned) and will then throw this error:
E/flutter ( 8726): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(Attempt to invoke virtual method 'void io.flutter.plugin.common.MethodChannel.invokeMethod(java.lang.String, java.lang.Object, io.flutter.plugin.common.MethodChannel$Result)' on a null object reference, null, null)
E/flutter ( 8726): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:572:7)
E/flutter ( 8726): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:161:18)
E/flutter ( 8726): <asynchronous suspension>
E/flutter ( 8726): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 8726): #3 AudioService.play (package:audio_service/audio_service.dart:895:20)
Here is my code which calls the start function:
if(AudioService.running) {
print('playing audio service: ${AudioService.running}');
AudioService.play();
} else {
MediaItem mediaItem = MediaItem(
id: newPostPod.audioUrl,
title: newPostPod.titleTextString(),
artist: newPostPod.subtitleTextString(),
);
print('starting audio service');
bool started = await AudioService.start(
backgroundTaskEntrypoint: _backgroundTaskEntrypoint,
params: {'mediaItem': mediaItem.toJson()},
);
print('audio service started');
if(AudioService.running) {
print('starting to play via media service');
AudioService.playMediaItem(mediaItem);
} else {
print('Audio Service not yet started: $started');
}
}
The code for the background task entrypoint (which is outside of any other class, as it wasn't working inside a class I had read in another issue that it had to be top-level):
_backgroundTaskEntrypoint() {
AudioServiceBackground.run(() => PlayerTask());
}
Lastly, it doesn't appear any of the code within my onStart in my BackgroundAudioTask is running (as print statements at the top of my onStart are not being run). So I'm not sure what's happening here. It isn't give me a clear error or really any hint of where to start debugging audio_service.
Calling AudioService.connect(); before starting the service will solve the error.
For me AudioService.start() would freeze until I added the WAKE_LOCK and FOREGROUND_SERVICE permissions to the AndroidManifest.xml file per the audio_service README file.