I can’t fetch the data from the post server, I get a fatal error
I have a link to a post server; I am trying to build a mini app to fetch and display data from this link in the App. I created network request to fetch the HTML
import 'package:http/http.dart' as http;
class NetworkService {
final String url;
NetworkService(this.url);
Future<String> fetchHtml() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to load HTML');
}
}
}
And display in WebView
`import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:graph_display_app/services/network_service.dart';
class GraphScreen extends StatefulWidget {
final String url;
const GraphScreen({Key? key, required this.url}) : super(key: key);
@override
_GraphScreenState createState() => _GraphScreenState();
}
class _GraphScreenState extends State<GraphScreen> {
late WebViewController controller;
String? htmlContent;
bool isLoading = true;
@override
void initState() {
super.initState();
fetchGraph();
}
Future<void> fetchGraph() async {
try {
NetworkService networkService = NetworkService(widget.url);
String html = await networkService.fetchHtml();
setState(() {
htmlContent = html;
isLoading = false;
controller = WebViewController()
..loadRequest(
Uri.dataFromString(
htmlContent!,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8'),
),
);
});
} catch (e) {
setState(() {
isLoading = false;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Failed to load graph')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Graph Viewer'),
),
body: isLoading
? const Center(child: CircularProgressIndicator())
: WebViewWidget(controller: controller),
);
}
}
I get a fatal error when I debug. Could it be the I have implemented wrongly?