In the process of developing iOS application with Flutter, there is a problem that HTTP response cannot be decoded with UTF-8, and I would like to solve it.
The Android Pixel 2 emulator was able to decode without any problems, so I think it is an iOS-specific problem.
The result is the result of running using tPhone 12 Pro Max emulator. (iOS Deployment Target=9.0)
This issue is that content of decoded_body_byte is null.
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:html/dom.dart' as dom;
import 'package:http/http.dart' as http;
import 'package:charset_converter/charset_converter.dart';
import 'package:flutter_user_agent/flutter_user_agent.dart';
// skip
String userAgent;
try {
userAgent = await FlutterUserAgent.getPropertyAsync('userAgent');
print("userAgent: ${userAgent}");
} on PlatformException {
userAgent = '<error>';
}
var response = await http.Client().get(Uri.parse("http://news4vip.livedoor.biz/archives/52385788.html"), headers: {'User-Agent': userAgent});
print("Response status: ${response.statusCode}");
print("response.headers: ${response.headers['content-type']}");
String decoded_body_byte = await CharsetConverter.decode("UTF-8", response.bodyBytes);
print("decoded_body_byte: ${decoded_body_byte}"); // ここの結果がnullになってしまうことが問題になっています。
Uint8List encoded = await CharsetConverter.encode("UTF-8", "【画像】中日「かっこいい」今季のユニホーム発表www");
print("encoded.length: ${encoded.length}");
String decoded_body_byte_only_title = await CharsetConverter.decode("UTF-8", response.bodyBytes.sublist(71, 71 + 78));
print("decoded_body_byte_only_title: ${decoded_body_byte_only_title}");
The following is the output result of the above code.
2021-01-23 17:09:29.964984+0900 Runner[89036:14458916] flutter: userAgent: CFNetwork/1209 Darwin/20.2.0 (iPhone iOS/14.3)
2021-01-23 17:09:30.187131+0900 Runner[89036:14458916] flutter: Response status: 200
2021-01-23 17:09:30.190547+0900 Runner[89036:14458916] flutter: response.headers: text/html; charset=utf-8
2021-01-23 17:09:30.195755+0900 Runner[89036:14458916] flutter: decoded_body_byte: null
2021-01-23 17:09:30.197368+0900 Runner[89036:14458916] flutter: encoded.length: 78
2021-01-23 17:09:30.198128+0900 Runner[89036:14458916] flutter: decoded_body_byte_only_title: 【画像】中日「かっこいい」今季のユニホーム発表www
Below is the output result of $ flutter doctor.
I would appreciate it if you could answer.
% flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 1.22.5, on macOS 11.1 20C69 darwin-x64, locale ja-JP)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
[✓] Xcode - develop for iOS and macOS (Xcode 12.3)
[!] Android Studio (version 4.1)
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] VS Code (version 1.52.1)
[✓] Connected device (2 available)
! Doctor found issues in 2 categories.
I can decode target web page using below Plugin instead of charset converter.
Maybe this http response included illegal character.
https://api.flutter.dev/flutter/dart-convert/Utf8Codec/decode.html
final decoded = Utf8Decoder(allowMalformed: true).convert(response.bodyBytes);
Related
I try to clean up my mobile flutter project: remove Podfile.lock, Podfile, .pub-cache
And then try to run flutter pub get. After than, when run flutter run I get this kind of error below. I still don't know how to fix:
../../../../Software/flutter/.pub-cache/hosted/pub.dartlang.org/syncfusion_flutter_pdfviewer-20.2.48-beta/lib/src/common/pdfviewer_plugin.dar
t:88:40: Error: The getter 'Uint8List' isn't defined for the class 'PdfViewerPlugin'.
- 'PdfViewerPlugin' is from 'package:syncfusion_flutter_pdfviewer/src/common/pdfviewer_plugin.dart'
('../../../../Software/flutter/.pub-cache/hosted/pub.dartlang.org/syncfusion_flutter_pdfviewer-20.2.48-beta/lib/src/common/pdfviewer_plugin.
dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'Uint8List'.
_renderedPages![pageIndex] = Uint8List.fromList(image);
^^^^^^^^^
../../../../Software/flutter/.pub-cache/hosted/pub.dartlang.org/fl_chart-0.46.0/lib/src/chart/pie_chart/pie_chart.dart:42:20: Warning:
Operand of null-aware operation '?.' has type 'WidgetsBinding' which excludes null.
- 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart'
('../../../../Software/flutter/packages/flutter/lib/src/widgets/binding.dart').
WidgetsBinding.instance?.addPostFrameCallback((_) {
^
../../../../Software/flutter/.pub-cache/hosted/pub.dartlang.org/syncfusion_pdfviewer_platform_interface-20.2.48-beta/lib/src/method_channel_p
dfviewer.dart:12:7: Error: 'Uint8List' isn't a type.
Uint8List documentBytes, String documentID) async {
^^^^^^^^^
../../../../Software/flutter/.pub-cache/hosted/pub.dartlang.org/syncfusion_pdfviewer_platform_interface-20.2.48-beta/lib/src/method_channel_p
dfviewer.dart:35:34: Error: 'Uint8List' isn't a type.
return _channel.invokeMethod<Uint8List>('getImage', <String, dynamic>{
^^^^^^^^^
Failed to package /Users/hoang/Works/Projects/unikgate/erest/erest_mobile.
Command PhaseScriptExecution failed with a nonzero exit code
Here is my flutter doctor -v
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.1, on macOS 12.1 21C52 darwin-x64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Community Edition (version 2021.1)
[✓] VS Code (version 1.71.0)
Can some one help me to solve this? Many thanks!
After upgrading flutter version from 2.2 to 2.5.3, permission_handler behaves abnormally.
PermissionStatus status = await Permission.photos.status;
print('## deny: ${status.isDenied}');
print('## grant: ${status.isGranted}');
print('## limit: ${status.isLimited}');
print('## permanently deny: ${status.isPermanentlyDenied}');
print('## restrict: ${status.isRestricted}');
if (!status.isGranted) {
await showDialog(
Even though access to all photos is allowed, the result is as follows.
flutter: ## deny: true
flutter: ## grant: false
flutter: ## limit: false
flutter: ## permanently deny: false
flutter: ## restrict: false
https://pub.dev/packages/permission_handler
I checked the above documentation but couldn't find a solution.
flutter doctor
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.3, on macOS 11.6 20G165 darwin-x64, locale ko-KR)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
✗ cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details.
✗ Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] Connected device (2 available)
! Doctor found issues in 1 category.
I use the plugin https://pub.dev/packages/image_picker
image_picker: ^0.8.0+3
on android the code runs fine on some devices, but when installed on ios, but when taking pictures with the camera, the application is stuck on the camera display
i using i phone 5 and i phone 10, but both stuck on camera display,
Button "Retake" and "Use Photo" cant click
here is my code
final pickedFile = await picker.getImage(
maxWidth: 800,
imageQuality: 85,
source: ImageSource.camera,
);
if (pickedFile != null) {
dPrint('Original path: ${pickedFile.path}');
String dir = path.dirname(pickedFile.path);
var timeStamp = DateTime.now().millisecondsSinceEpoch;
var fileName = "IMG_" + timeStamp.toString() + ".jpg";
String newPath = path.join(dir, fileName);
File newFile = await File(pickedFile.path).copy(newPath);
if (newFile != null) {
print(newFile);
}
}
Flutter doctor result :
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.0, on Mac OS X 10.15.7 19H2 darwin-x64, locale en-ID)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] Connected device (1 available)
! Doctor found issues in 1 category.
Flutter 2.0.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 60bd88df91 (3 months ago) • 2021-03-03 09:13:17 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0
You need to tap on Use Photo to get the image captured
I've been using the 'firebase_ml_vision' package to scan Qr codes in an Image Stream provided by the 'camera' package. Everything was fine until the update that happened in Nov. 6. In Android, I can still scan qr codes without problems. But in iOS, i'm having the app is throwing the Exception: PlatformException(Error 13, com.firebase.ml, Barcode engine is nil., null)
I've updated my podfile with the line pod 'GoogleMLKit/BarcodeScanning', because the command 'flutter build ios' finished with an error when the Podfile had pod 'Firebase/MLVisionBarcodeModel' instead. I did because the pod update command explained that the package 'Firebase/MLVisionBarcodeModel' was deprecated, and thought it was the source of the problem.
Still the problem keeps happening.
Flutter doctor -v output:
[✓] Flutter (Channel stable, 1.22.4, on Mac OS X 10.15.6 19G73 darwin-x64, locale en-EC)
• Flutter version 1.22.4 at /Applications/flutter_sdk/jaime/flutter
• Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
• Engine revision 2c956a31c0
• Dart version 2.10.4
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/jvasquez/Library/Android/sdk
• Platform android-29, build-tools 29.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 12.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.1, Build version 12A7403
• CocoaPods version 1.10.0
[✓] Android Studio (version 4.0)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 46.0.2
• Dart plugin version 193.7361
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
[✓] VS Code (version 1.51.0)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.16.0
[!] Connected device
! No devices available
! Doctor found issues in 1 category.
This is the code I use to analyze the CameraImage:
static Future<List<Barcode>> detect({
#required CameraImage image,
// #required BarcodeDetector detector,
#required int imageRotation,
}) async {
var rp = List<Barcode>();
try {
BarcodeDetector detector = FirebaseVision.instance.barcodeDetector(
BarcodeDetectorOptions(
barcodeFormats: BarcodeFormat.qrCode,
)
);
var metadata = _buildMetaData(image, _rotationIntToImageRotation(imageRotation));
FirebaseVisionImage visionImage = FirebaseVisionImage.fromBytes(_concatenatePlanes(image.planes), metadata);
rp = await detector.detectInImage(visionImage);
} catch (ex) {
print("Ocurrió un error: $ex");
// UtilFunctions.escribirEnLog(
// mensaje: "$ex",
// nombreFuncion: "detect",
// tipo: 0,
// );
}
return rp;
}
static Uint8List _concatenatePlanes(List<Plane> planes) {
final WriteBuffer allBytes = WriteBuffer();
for (Plane plane in planes) {
allBytes.putUint8List(plane.bytes);
}
return allBytes.done().buffer.asUint8List();
}
The problem is, that firebase_ml_vision internally uses Firebase/MLVisionBarcodeModel and not GoogleMLKit/BarcodeScanning.
In the issue https://github.com/FirebaseExtended/flutterfire/issues/4625 another user forked the firebase_ml_vision package and adjusted it to work with GoogleMLKit/BarcodeScanning. There is also a PR for this form (https://github.com/FirebaseExtended/flutterfire/pull/5378).
It is important to mention that some functionality, especially cloud functionality, has been removed to make it work.
Therefore, this could break parts of your app where these features are missing and it is yet not a great solution.
To use the forked package include the following in your Pubspec.yaml
firebase_ml_vision:
git:
url: git://github.com/algirdasmac/flutterfire
path: packages/firebase_ml_vision
I'm using the multicast_dns package for Flutter and get an exception on iOS.
It works as expected on Android. I have tested this with the code example provided with the package, see https://pub.dev/packages/multicast_dns
The error is:
OS Error: Can't assign requested address, errno = 49 in
_NativeSocket.joinMulticast. (socket_patch.dart)
I have tried various multicast addresses, the default 224.0.0.251, 230.180.0.1 and 239.0.180.1.
import 'package:multicast_dns/multicast_dns.dart';
Future<void> main() async {
const String name = '_dartobservatory._tcp.local';
final MDnsClient client = MDnsClient();
await client.start(mDnsAddress: InternetAddress('239.0.180.1'));
await for (PtrResourceRecord ptr in client
.lookup<PtrResourceRecord>(ResourceRecordQuery.serverPointer(name))) {
await for (SrvResourceRecord srv in client.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(ptr.domainName))) {
final String bundleId =
ptr.domainName; //.substring(0, ptr.domainName.indexOf('#'));
print('Dart observatory instance found at '
'${srv.target}:${srv.port} for "$bundleId".');
}
}
client.stop();
print('Done.');
}
Flutter doctor:
mdnstest $ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.14.5 18F203, locale
en)
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
✗ Android licenses not accepted. To resolve this, run: flutter doctor
--android-licenses
[✓] Xcode - develop for iOS and macOS (Xcode 11.0)
[✓] Android Studio (version 3.5)
[✓] Connected device (1 available)
! Doctor found issues in 1 category.