We are currently working on a project for our studygroup and encountered a bug while testing.
One (and only one) of our dart pages isnt getting displayed on the emulator within Android Studio when using an API Level of 34. Anything below that works.
Below is the code of the dartpage:
<code>import 'dart:convert';
import 'dart:io';
import 'package:apf_at_work/Arbeitsschutz/quiz_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Keys.dart';
import '../appbar.dart';
import '../customVideoPlayer.dart';
import '../styles.dart';
class ArbeitsschutzPage extends StatefulWidget {
const ArbeitsschutzPage({super.key});
@override
State<ArbeitsschutzPage> createState() => _ArbeitsschutzPageState();
}
class _ArbeitsschutzPageState extends State<ArbeitsschutzPage> {
Future<List<Widget>> mediaListFuture = Future.value([]);
@override
void initState() {
super.initState();
loadPreferencesAndFetchMedia();
}
Future<void> loadPreferencesAndFetchMedia() async {
setState(() {
mediaListFuture = Future.value([]); // Resetting the future to avoid using old data
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final bool standard = prefs.getBool('login_standard_key') ?? false;
final bool production = prefs.getBool('login_production_key') ?? false;
print('Standard: $standard, Production: $production');
mediaListFuture = fetchMediaBasedOnPermissions(standard, production);
if (mounted) {
setState(() {}); // This will trigger the FutureBuilder to rebuild with new data
}
}
Future<List<Widget>> fetchMediaBasedOnPermissions(bool standard, bool production) async {
const String apiUrl = '$baseUrl/api/arbeitsschutzs';
List<String> queries = [];
if (standard) queries.add('Standard_eq=true');
if (production) queries.add('Produktion_eq=true');
final String filterQuery = queries.isNotEmpty ? queries.join('&') : 'Standard_eq=false&Produktion_eq=false';
final String query = '?populate=*&$filterQuery';
final Uri fullUri = Uri.parse(apiUrl + query);
try {
final response = await http.get(fullUri, headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $STRAPI_API_TOKEN',
});
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body)['data'];
List<Widget> widgets = [];
SharedPreferences prefs = await SharedPreferences.getInstance();
for (var item in data) {
final attributes = item['attributes'];
final bool itemStandard = attributes['Standard'];
final bool itemProduction = attributes['Production'];
final String itemId = 'quiz_${item['id']}'; // Unique ID for each item's quiz
final String? quizUrl = attributes['Quiz'];
bool quizCompleted = prefs.getBool(itemId) ?? false;
if ((production && itemProduction) || (standard && itemStandard)) {
final media = attributes['ArbeitsschutzMedia']['data'].isNotEmpty ? attributes['ArbeitsschutzMedia']['data'][0] : null;
final mediaUrl = media != null ? '$baseUrl${media['attributes']['url']}' : null;
final mimeType = media != null ? media['attributes']['mime'] : 'text/plain';
final bool isVideo = mimeType.contains('video');
final bool hasQuiz = quizUrl != null && quizUrl.isNotEmpty;
if (isVideo) {
quizCompleted = prefs.getBool(itemId) ?? false;
}
IconData? icon = isVideo && hasQuiz
? (quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked)
: null; // Conditional icon based on quiz status and media type
Color iconColor = isVideo && hasQuiz ? (quizCompleted ? Colors.green : Colors.red) : Colors.transparent;
widgets.add(ListTile(
title: Text(attributes['Titel'] ?? 'No Title', style: textStyle),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MediaDisplayPage(
mediaUrl: mediaUrl,
mimeType: mimeType,
title: attributes['Titel'],
quizId: hasQuiz ? itemId : null,
// Pass quizId only for videos with a quiz
quizUrl: quizUrl,
// Pass the dynamic quiz URL
onQuizCompleted: () async {
print("Handling quiz completion in parent page.");
await loadPreferencesAndFetchMedia(); // This should refetch and update the UI accordingly
},
),
),
),
trailing: isVideo && hasQuiz
? Icon(
quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked,
color: quizCompleted ? Colors.green : Colors.red,
)
: null, // Show icon only for videos with a quiz
));
print('Media Title: ${attributes['Titel']}');
print('Media URL: $mediaUrl');
print('MIME Type: $mimeType');
}
}
return widgets;
} else {
throw Exception('Failed to load media with status code: ${response.statusCode}');
}
} catch (e) {
print('Error fetching media: $e');
throw Exception('Failed to load media: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar("Arbeitsschutz"),
body: FutureBuilder<List<Widget>>(
future: mediaListFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
print('FutureBuilder Error: ${snapshot.error}');
return Text('Error: ${snapshot.error}');
} else {
return ListView(children: snapshot.data ?? []);
}
},
),
);
}
}
class MediaDisplayPage extends StatefulWidget {
final String? mediaUrl;
final String? mimeType;
final String? title;
final String? quizId;
final String? quizUrl;
final VoidCallback? onQuizCompleted;
const MediaDisplayPage({super.key, this.mediaUrl, this.mimeType, this.title, required this.quizId, this.quizUrl, this.onQuizCompleted});
@override
State<MediaDisplayPage> createState() => _MediaDisplayPageState();
}
class _MediaDisplayPageState extends State<MediaDisplayPage> {
String? localPath;
bool isLoading = true;
PDFViewController? controller;
int totalPages = 0;
int currentPage = 0;
@override
void initState() {
super.initState();
if (widget.mediaUrl != null && widget.mimeType!.contains('pdf')) {
downloadFile(widget.mediaUrl!);
} else {
localPath = widget.mediaUrl;
isLoading = false;
}
}
Future<void> downloadFile(String url) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/pdf.pdf');
await file.writeAsBytes(bytes, flush: true);
localPath = file.path;
if (mounted) {
setState(() => isLoading = false);
}
}
@override
void dispose() {
if (localPath != null && widget.mimeType!.contains('pdf')) {
final file = File(localPath!);
if (file.existsSync()) {
file.delete();
}
}
super.dispose();
}
@override
Widget build(BuildContext context) {
if (isLoading) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Datei wird geladen...'),
body: const Center(child: CircularProgressIndicator()),
);
}
if (localPath == null) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Error'),
body: const Center(child: Text('Fehler beim Laden der Datei')),
);
}
Widget contentWidget;
if (widget.mimeType!.contains('image')) {
// Wrap the image with an InteractiveViewer for zooming capability
contentWidget = InteractiveViewer(
minScale: 0.5,
maxScale: 4.0,
child: Center(
child: Image.network(
localPath!,
width: MediaQuery.of(context).size.width, // Set image width to match device width
fit: BoxFit.contain, // Use BoxFit to ensure the aspect ratio is maintained
),
),
);
} else if (widget.mimeType!.contains('pdf')) {
contentWidget = SizedBox(
height: MediaQuery.of(context).size.height,
child: PDFView(
filePath: localPath,
enableSwipe: true,
swipeHorizontal: false,
autoSpacing: false,
pageFling: true,
pageSnap: true,
fitPolicy: FitPolicy.WIDTH,
nightMode: false,
onError: (error) {
print("Error loading PDF: $error");
},
onRender: (pages) {
totalPages = pages!;
setState(() {});
},
onViewCreated: (PDFViewController pdfViewController) {
controller = pdfViewController;
},
onPageChanged: (int? current, int? total) {
setState(() {
currentPage = current ?? 0;
});
},
onPageError: (page, error) {
print('$page: ${error.toString()}');
},
),
);
} else if (widget.mimeType!.contains('video')) {
bool isQuizPromptShown = false; // to prevent dialog from appearing multiple times
contentWidget = CustomVideoPlayer(
url: localPath!,
mimeType: widget.mimeType!,
onVideoComplete: () {
if (!isQuizPromptShown && widget.quizId != null && widget.quizUrl != null) {
// Ensure quizId and QuizUrl is not null
isQuizPromptShown = true; // Set the flag to true to prevent re-triggering
showQuizDialog(context, widget.quizUrl!, widget.quizId!, () {
// This callback will be triggered after the quiz is completed successfully.
print("Quiz completion callback triggered.");
widget.onQuizCompleted!(); // Call the passed callback to refresh the parent state
});
}
},
);
} else {
contentWidget = const Center(child: Text('Dateiformat wird nicht unterstützt'));
}
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Fehler beim Anzeigen des Namens'),
body: contentWidget,
);
}
}
</code>
<code>import 'dart:convert';
import 'dart:io';
import 'package:apf_at_work/Arbeitsschutz/quiz_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Keys.dart';
import '../appbar.dart';
import '../customVideoPlayer.dart';
import '../styles.dart';
class ArbeitsschutzPage extends StatefulWidget {
const ArbeitsschutzPage({super.key});
@override
State<ArbeitsschutzPage> createState() => _ArbeitsschutzPageState();
}
class _ArbeitsschutzPageState extends State<ArbeitsschutzPage> {
Future<List<Widget>> mediaListFuture = Future.value([]);
@override
void initState() {
super.initState();
loadPreferencesAndFetchMedia();
}
Future<void> loadPreferencesAndFetchMedia() async {
setState(() {
mediaListFuture = Future.value([]); // Resetting the future to avoid using old data
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final bool standard = prefs.getBool('login_standard_key') ?? false;
final bool production = prefs.getBool('login_production_key') ?? false;
print('Standard: $standard, Production: $production');
mediaListFuture = fetchMediaBasedOnPermissions(standard, production);
if (mounted) {
setState(() {}); // This will trigger the FutureBuilder to rebuild with new data
}
}
Future<List<Widget>> fetchMediaBasedOnPermissions(bool standard, bool production) async {
const String apiUrl = '$baseUrl/api/arbeitsschutzs';
List<String> queries = [];
if (standard) queries.add('Standard_eq=true');
if (production) queries.add('Produktion_eq=true');
final String filterQuery = queries.isNotEmpty ? queries.join('&') : 'Standard_eq=false&Produktion_eq=false';
final String query = '?populate=*&$filterQuery';
final Uri fullUri = Uri.parse(apiUrl + query);
try {
final response = await http.get(fullUri, headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $STRAPI_API_TOKEN',
});
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body)['data'];
List<Widget> widgets = [];
SharedPreferences prefs = await SharedPreferences.getInstance();
for (var item in data) {
final attributes = item['attributes'];
final bool itemStandard = attributes['Standard'];
final bool itemProduction = attributes['Production'];
final String itemId = 'quiz_${item['id']}'; // Unique ID for each item's quiz
final String? quizUrl = attributes['Quiz'];
bool quizCompleted = prefs.getBool(itemId) ?? false;
if ((production && itemProduction) || (standard && itemStandard)) {
final media = attributes['ArbeitsschutzMedia']['data'].isNotEmpty ? attributes['ArbeitsschutzMedia']['data'][0] : null;
final mediaUrl = media != null ? '$baseUrl${media['attributes']['url']}' : null;
final mimeType = media != null ? media['attributes']['mime'] : 'text/plain';
final bool isVideo = mimeType.contains('video');
final bool hasQuiz = quizUrl != null && quizUrl.isNotEmpty;
if (isVideo) {
quizCompleted = prefs.getBool(itemId) ?? false;
}
IconData? icon = isVideo && hasQuiz
? (quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked)
: null; // Conditional icon based on quiz status and media type
Color iconColor = isVideo && hasQuiz ? (quizCompleted ? Colors.green : Colors.red) : Colors.transparent;
widgets.add(ListTile(
title: Text(attributes['Titel'] ?? 'No Title', style: textStyle),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MediaDisplayPage(
mediaUrl: mediaUrl,
mimeType: mimeType,
title: attributes['Titel'],
quizId: hasQuiz ? itemId : null,
// Pass quizId only for videos with a quiz
quizUrl: quizUrl,
// Pass the dynamic quiz URL
onQuizCompleted: () async {
print("Handling quiz completion in parent page.");
await loadPreferencesAndFetchMedia(); // This should refetch and update the UI accordingly
},
),
),
),
trailing: isVideo && hasQuiz
? Icon(
quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked,
color: quizCompleted ? Colors.green : Colors.red,
)
: null, // Show icon only for videos with a quiz
));
print('Media Title: ${attributes['Titel']}');
print('Media URL: $mediaUrl');
print('MIME Type: $mimeType');
}
}
return widgets;
} else {
throw Exception('Failed to load media with status code: ${response.statusCode}');
}
} catch (e) {
print('Error fetching media: $e');
throw Exception('Failed to load media: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar("Arbeitsschutz"),
body: FutureBuilder<List<Widget>>(
future: mediaListFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
print('FutureBuilder Error: ${snapshot.error}');
return Text('Error: ${snapshot.error}');
} else {
return ListView(children: snapshot.data ?? []);
}
},
),
);
}
}
class MediaDisplayPage extends StatefulWidget {
final String? mediaUrl;
final String? mimeType;
final String? title;
final String? quizId;
final String? quizUrl;
final VoidCallback? onQuizCompleted;
const MediaDisplayPage({super.key, this.mediaUrl, this.mimeType, this.title, required this.quizId, this.quizUrl, this.onQuizCompleted});
@override
State<MediaDisplayPage> createState() => _MediaDisplayPageState();
}
class _MediaDisplayPageState extends State<MediaDisplayPage> {
String? localPath;
bool isLoading = true;
PDFViewController? controller;
int totalPages = 0;
int currentPage = 0;
@override
void initState() {
super.initState();
if (widget.mediaUrl != null && widget.mimeType!.contains('pdf')) {
downloadFile(widget.mediaUrl!);
} else {
localPath = widget.mediaUrl;
isLoading = false;
}
}
Future<void> downloadFile(String url) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/pdf.pdf');
await file.writeAsBytes(bytes, flush: true);
localPath = file.path;
if (mounted) {
setState(() => isLoading = false);
}
}
@override
void dispose() {
if (localPath != null && widget.mimeType!.contains('pdf')) {
final file = File(localPath!);
if (file.existsSync()) {
file.delete();
}
}
super.dispose();
}
@override
Widget build(BuildContext context) {
if (isLoading) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Datei wird geladen...'),
body: const Center(child: CircularProgressIndicator()),
);
}
if (localPath == null) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Error'),
body: const Center(child: Text('Fehler beim Laden der Datei')),
);
}
Widget contentWidget;
if (widget.mimeType!.contains('image')) {
// Wrap the image with an InteractiveViewer for zooming capability
contentWidget = InteractiveViewer(
minScale: 0.5,
maxScale: 4.0,
child: Center(
child: Image.network(
localPath!,
width: MediaQuery.of(context).size.width, // Set image width to match device width
fit: BoxFit.contain, // Use BoxFit to ensure the aspect ratio is maintained
),
),
);
} else if (widget.mimeType!.contains('pdf')) {
contentWidget = SizedBox(
height: MediaQuery.of(context).size.height,
child: PDFView(
filePath: localPath,
enableSwipe: true,
swipeHorizontal: false,
autoSpacing: false,
pageFling: true,
pageSnap: true,
fitPolicy: FitPolicy.WIDTH,
nightMode: false,
onError: (error) {
print("Error loading PDF: $error");
},
onRender: (pages) {
totalPages = pages!;
setState(() {});
},
onViewCreated: (PDFViewController pdfViewController) {
controller = pdfViewController;
},
onPageChanged: (int? current, int? total) {
setState(() {
currentPage = current ?? 0;
});
},
onPageError: (page, error) {
print('$page: ${error.toString()}');
},
),
);
} else if (widget.mimeType!.contains('video')) {
bool isQuizPromptShown = false; // to prevent dialog from appearing multiple times
contentWidget = CustomVideoPlayer(
url: localPath!,
mimeType: widget.mimeType!,
onVideoComplete: () {
if (!isQuizPromptShown && widget.quizId != null && widget.quizUrl != null) {
// Ensure quizId and QuizUrl is not null
isQuizPromptShown = true; // Set the flag to true to prevent re-triggering
showQuizDialog(context, widget.quizUrl!, widget.quizId!, () {
// This callback will be triggered after the quiz is completed successfully.
print("Quiz completion callback triggered.");
widget.onQuizCompleted!(); // Call the passed callback to refresh the parent state
});
}
},
);
} else {
contentWidget = const Center(child: Text('Dateiformat wird nicht unterstützt'));
}
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Fehler beim Anzeigen des Namens'),
body: contentWidget,
);
}
}
</code>
import 'dart:convert';
import 'dart:io';
import 'package:apf_at_work/Arbeitsschutz/quiz_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Keys.dart';
import '../appbar.dart';
import '../customVideoPlayer.dart';
import '../styles.dart';
class ArbeitsschutzPage extends StatefulWidget {
const ArbeitsschutzPage({super.key});
@override
State<ArbeitsschutzPage> createState() => _ArbeitsschutzPageState();
}
class _ArbeitsschutzPageState extends State<ArbeitsschutzPage> {
Future<List<Widget>> mediaListFuture = Future.value([]);
@override
void initState() {
super.initState();
loadPreferencesAndFetchMedia();
}
Future<void> loadPreferencesAndFetchMedia() async {
setState(() {
mediaListFuture = Future.value([]); // Resetting the future to avoid using old data
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final bool standard = prefs.getBool('login_standard_key') ?? false;
final bool production = prefs.getBool('login_production_key') ?? false;
print('Standard: $standard, Production: $production');
mediaListFuture = fetchMediaBasedOnPermissions(standard, production);
if (mounted) {
setState(() {}); // This will trigger the FutureBuilder to rebuild with new data
}
}
Future<List<Widget>> fetchMediaBasedOnPermissions(bool standard, bool production) async {
const String apiUrl = '$baseUrl/api/arbeitsschutzs';
List<String> queries = [];
if (standard) queries.add('Standard_eq=true');
if (production) queries.add('Produktion_eq=true');
final String filterQuery = queries.isNotEmpty ? queries.join('&') : 'Standard_eq=false&Produktion_eq=false';
final String query = '?populate=*&$filterQuery';
final Uri fullUri = Uri.parse(apiUrl + query);
try {
final response = await http.get(fullUri, headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $STRAPI_API_TOKEN',
});
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body)['data'];
List<Widget> widgets = [];
SharedPreferences prefs = await SharedPreferences.getInstance();
for (var item in data) {
final attributes = item['attributes'];
final bool itemStandard = attributes['Standard'];
final bool itemProduction = attributes['Production'];
final String itemId = 'quiz_${item['id']}'; // Unique ID for each item's quiz
final String? quizUrl = attributes['Quiz'];
bool quizCompleted = prefs.getBool(itemId) ?? false;
if ((production && itemProduction) || (standard && itemStandard)) {
final media = attributes['ArbeitsschutzMedia']['data'].isNotEmpty ? attributes['ArbeitsschutzMedia']['data'][0] : null;
final mediaUrl = media != null ? '$baseUrl${media['attributes']['url']}' : null;
final mimeType = media != null ? media['attributes']['mime'] : 'text/plain';
final bool isVideo = mimeType.contains('video');
final bool hasQuiz = quizUrl != null && quizUrl.isNotEmpty;
if (isVideo) {
quizCompleted = prefs.getBool(itemId) ?? false;
}
IconData? icon = isVideo && hasQuiz
? (quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked)
: null; // Conditional icon based on quiz status and media type
Color iconColor = isVideo && hasQuiz ? (quizCompleted ? Colors.green : Colors.red) : Colors.transparent;
widgets.add(ListTile(
title: Text(attributes['Titel'] ?? 'No Title', style: textStyle),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MediaDisplayPage(
mediaUrl: mediaUrl,
mimeType: mimeType,
title: attributes['Titel'],
quizId: hasQuiz ? itemId : null,
// Pass quizId only for videos with a quiz
quizUrl: quizUrl,
// Pass the dynamic quiz URL
onQuizCompleted: () async {
print("Handling quiz completion in parent page.");
await loadPreferencesAndFetchMedia(); // This should refetch and update the UI accordingly
},
),
),
),
trailing: isVideo && hasQuiz
? Icon(
quizCompleted ? Icons.check_circle_outline : Icons.radio_button_unchecked,
color: quizCompleted ? Colors.green : Colors.red,
)
: null, // Show icon only for videos with a quiz
));
print('Media Title: ${attributes['Titel']}');
print('Media URL: $mediaUrl');
print('MIME Type: $mimeType');
}
}
return widgets;
} else {
throw Exception('Failed to load media with status code: ${response.statusCode}');
}
} catch (e) {
print('Error fetching media: $e');
throw Exception('Failed to load media: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar("Arbeitsschutz"),
body: FutureBuilder<List<Widget>>(
future: mediaListFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
print('FutureBuilder Error: ${snapshot.error}');
return Text('Error: ${snapshot.error}');
} else {
return ListView(children: snapshot.data ?? []);
}
},
),
);
}
}
class MediaDisplayPage extends StatefulWidget {
final String? mediaUrl;
final String? mimeType;
final String? title;
final String? quizId;
final String? quizUrl;
final VoidCallback? onQuizCompleted;
const MediaDisplayPage({super.key, this.mediaUrl, this.mimeType, this.title, required this.quizId, this.quizUrl, this.onQuizCompleted});
@override
State<MediaDisplayPage> createState() => _MediaDisplayPageState();
}
class _MediaDisplayPageState extends State<MediaDisplayPage> {
String? localPath;
bool isLoading = true;
PDFViewController? controller;
int totalPages = 0;
int currentPage = 0;
@override
void initState() {
super.initState();
if (widget.mediaUrl != null && widget.mimeType!.contains('pdf')) {
downloadFile(widget.mediaUrl!);
} else {
localPath = widget.mediaUrl;
isLoading = false;
}
}
Future<void> downloadFile(String url) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/pdf.pdf');
await file.writeAsBytes(bytes, flush: true);
localPath = file.path;
if (mounted) {
setState(() => isLoading = false);
}
}
@override
void dispose() {
if (localPath != null && widget.mimeType!.contains('pdf')) {
final file = File(localPath!);
if (file.existsSync()) {
file.delete();
}
}
super.dispose();
}
@override
Widget build(BuildContext context) {
if (isLoading) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Datei wird geladen...'),
body: const Center(child: CircularProgressIndicator()),
);
}
if (localPath == null) {
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Error'),
body: const Center(child: Text('Fehler beim Laden der Datei')),
);
}
Widget contentWidget;
if (widget.mimeType!.contains('image')) {
// Wrap the image with an InteractiveViewer for zooming capability
contentWidget = InteractiveViewer(
minScale: 0.5,
maxScale: 4.0,
child: Center(
child: Image.network(
localPath!,
width: MediaQuery.of(context).size.width, // Set image width to match device width
fit: BoxFit.contain, // Use BoxFit to ensure the aspect ratio is maintained
),
),
);
} else if (widget.mimeType!.contains('pdf')) {
contentWidget = SizedBox(
height: MediaQuery.of(context).size.height,
child: PDFView(
filePath: localPath,
enableSwipe: true,
swipeHorizontal: false,
autoSpacing: false,
pageFling: true,
pageSnap: true,
fitPolicy: FitPolicy.WIDTH,
nightMode: false,
onError: (error) {
print("Error loading PDF: $error");
},
onRender: (pages) {
totalPages = pages!;
setState(() {});
},
onViewCreated: (PDFViewController pdfViewController) {
controller = pdfViewController;
},
onPageChanged: (int? current, int? total) {
setState(() {
currentPage = current ?? 0;
});
},
onPageError: (page, error) {
print('$page: ${error.toString()}');
},
),
);
} else if (widget.mimeType!.contains('video')) {
bool isQuizPromptShown = false; // to prevent dialog from appearing multiple times
contentWidget = CustomVideoPlayer(
url: localPath!,
mimeType: widget.mimeType!,
onVideoComplete: () {
if (!isQuizPromptShown && widget.quizId != null && widget.quizUrl != null) {
// Ensure quizId and QuizUrl is not null
isQuizPromptShown = true; // Set the flag to true to prevent re-triggering
showQuizDialog(context, widget.quizUrl!, widget.quizId!, () {
// This callback will be triggered after the quiz is completed successfully.
print("Quiz completion callback triggered.");
widget.onQuizCompleted!(); // Call the passed callback to refresh the parent state
});
}
},
);
} else {
contentWidget = const Center(child: Text('Dateiformat wird nicht unterstützt'));
}
return Scaffold(
appBar: ArrowCustomAppBar(widget.title ?? 'Fehler beim Anzeigen des Namens'),
body: contentWidget,
);
}
}
Below is the app/build.gradle page:
<code>plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.google.gms.google-services'
android {
namespace "com.example.apf_at_work"
compileSdkVersion 34
ndkVersion flutter.ndkVersion
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.apf_at_work"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deploymenSt/android#reviewing-the-gradle-build-configuration.
minSdkVersion 21
targetSdkVersion 34
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so flutter run --release works.
signingConfig signingConfigs. debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.2'
implementation 'androidx.window:window:1.0.0'
implementation 'androidx.window:window-java:1.0.0'
}
</code>
<code>plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.google.gms.google-services'
android {
namespace "com.example.apf_at_work"
compileSdkVersion 34
ndkVersion flutter.ndkVersion
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.apf_at_work"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deploymenSt/android#reviewing-the-gradle-build-configuration.
minSdkVersion 21
targetSdkVersion 34
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so flutter run --release works.
signingConfig signingConfigs. debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.2'
implementation 'androidx.window:window:1.0.0'
implementation 'androidx.window:window-java:1.0.0'
}
</code>
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.google.gms.google-services'
android {
namespace "com.example.apf_at_work"
compileSdkVersion 34
ndkVersion flutter.ndkVersion
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.apf_at_work"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deploymenSt/android#reviewing-the-gradle-build-configuration.
minSdkVersion 21
targetSdkVersion 34
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so flutter run --release works.
signingConfig signingConfigs. debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.2'
implementation 'androidx.window:window:1.0.0'
implementation 'androidx.window:window-java:1.0.0'
}
Steps:
Started emulation with API Level 34
Ran app on the emulated phone
Expected:
Dartpage works and is displayed as usual
Result:
Blank Page, except for the appbar, home button and the top icon