Разработка приложений Flutter: несовместимость epub_view, dart:io и Universal_io. Как решить?IOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Разработка приложений Flutter: несовместимость epub_view, dart:io и Universal_io. Как решить?

Сообщение Anonymous »

Я пытаюсь создать кроссплатформенное приложение для чтения электронных книг во Flutter. Чтобы обеспечить совместимость с Интернетом, я использовал

Код: Выделить всё

universal_io. НО пакет epub_view, очевидно, не поддерживает Universal_io
, а исключительно dart:io... а для приложения для чтения электронных книг поддержка epub необходима.
Чтобы справиться с этой проблемой, я попытался условно использовать dart:io.File для невеб-платформ, исключив его в сети.
Ошибка, от которой я не могу избавиться. :

Код: Выделить всё

flutter run -d chrome
Launching lib\main.dart on Chrome in debug mode...
lib/src/features/book_reader/components/epub_viewer.dart:58:41: Error: The argument type 'File/*1*/' can't be assigned to the parameter type 'File/*2*/'.
- 'File/*1*/' is from 'dart:io'.
- 'File/*2*/' is from 'package:universal_file/src/io/file.dart' ('/C:/Users/Larry/AppData/Local/Pub/Cache/hosted/pub.dev/universal_file-1.0.0/lib/src/io/file.dart').
document: EpubDocument.openFile(file),
^
Вот последняя версия моего кода, включая мои попытки решить эту проблему:
  • Использование условного импорта с if (dart.library.html) для выборочного импорта dart:io или Universal_io.
  • Добавление явных псевдонимов (

    Код: Выделить всё

    dart_io.File
    и Universal_io.File), чтобы избежать двусмысленности типов.
  • Гарантия того, что код dart:io не будет выполняться в Интернете, с помощью защиты с помощью kIsWeb .

Код: Выделить всё

// src/features/book_reader/components/epub_viewer.dart
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:epub_view/epub_view.dart';

// Explicitly import dart:io with an alias
import 'dart:io' as dart_io;

// Explicitly import universal_io with an alias
import 'package:universal_io/io.dart' as universal_io;

class EpubViewerScreen extends StatefulWidget {
final String filePath;
final String? title;
final Function(double)? onProgressChanged;
final double initialProgress;

const EpubViewerScreen({
Key? key,
required this.filePath,
this.title,
this.onProgressChanged,
this.initialProgress = 0.0,
}) : super(key: key);

@override
State createState() => _EpubViewerScreenState();
}

class _EpubViewerScreenState extends State {
late EpubController _epubController;
bool _isLoading = true;
String? _errorMessage;

@override
void initState() {
super.initState();
_loadBook();
}

Future  _loadBook() async {
try {
if (kIsWeb) {
// EPUB not supported on the web
throw UnsupportedError('EPUB viewing is not supported on the web.');
}

// Use dart:io.File for non-web platforms
final dart_io.File file = dart_io.File(widget.filePath);

// Ensure the file exists
if (!await file.exists()) {
throw dart_io.FileSystemException('File not found', widget.filePath);
}

// Initialize the EpubController with the dart:io.File
_epubController = EpubController(
document: EpubDocument.openFile(file),
);

setState(() {
_isLoading = false;
_errorMessage = null;
});
} catch (e) {
setState(() {
_errorMessage = 'Error loading EPUB: ${e.toString()}';
_isLoading = false;
});
}
}

@override
Widget build(BuildContext context) {
if (kIsWeb) {
return Scaffold(
appBar: AppBar(title: Text(widget.title ?? 'EPUB Reader')),
body: const Center(
child: Text('EPUB viewing is not supported on the web platform.'),
),
);
}

if (_isLoading) {
return Scaffold(
appBar: AppBar(title: Text(widget.title ?? 'EPUB Reader')),
body: const Center(child: CircularProgressIndicator()),
);
}

if (_errorMessage != null) {
return Scaffold(
appBar: AppBar(title: Text(widget.title ?? 'EPUB Reader')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 48),
const SizedBox(height: 16),
Text(
_errorMessage!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 16),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _loadBook,
child: const Text('Retry'),
),
],
),
),
),
);
}

return Scaffold(
appBar: AppBar(
title: Text(widget.title ?? 'EPUB Reader'),
),
body: EpubView(
controller: _epubController,
onChapterChanged: (chapter) {
if (widget.onProgressChanged != null && chapter != null) {
widget.onProgressChanged!(0.5);
}
},
),
);
}

@override
void dispose() {
_epubController.dispose();
super.dispose();
}
}
Итак,
  • Есть ли способ полностью изолировать тип dart:io.File, чтобы он не конфликтует с Universal_io.File?
  • Есть ли лучшие способы обеспечить кросс-платформенную совместимость для обработки файлов в этой ситуации? Например, существуют ли кроссплатформенные альтернативы epub_view, совместимые с Universal_io?


Подробнее здесь: https://stackoverflow.com/questions/792 ... tibility-h
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»