I am fairly new to Flutter and am converting a React Native app to Flutter. I am struggling with an example from the flutter documentation to read a json file from the cloud.
https://docs.flutter.dev/cookbook/networking/fetch-data
In my application, I want to read a list of “Albums” like in the example code. But it seems no matter what I try, I run into different errors. This is the closest I have come to get it working. Basically it is identical to the Album example except that I make it a List of Albums, I use my JSON file and my class for decoding the JSON.
When I run it, on line 96 List<Future<EngagementText>> futureAlbum = [];
I get:
Exception has occurred.
RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)
I have tried many things and continue to get different errors based on all the different approaches I have taken.
Here is the code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// Used my class instead of album
Future<EngagementText> fetchAlbum() async {
final response = await http.get(Uri.parse(
'https://ListeningToGod.org/SermonEngagement/TextFiles/2024-09-0801a.json'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return EngagementText.fromJson(
jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
// *** USED my class instead of album
class EngagementText {
String? version;
String? date;
String? text;
List<Links>? links;
EngagementText({this.version, this.date, this.text, this.links});
EngagementText.fromJson(Map<String, dynamic> json) {
try {
version = json['version'];
date = json['date'];
text = json['text'];
if (json['links'] != null) {
links = <Links>[];
json['links'].forEach((v) {
links!.add(Links.fromJson(v));
});
}
} catch (e) {
date = "2024-01-01";
text = "Dummy Text";
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['version'] = version;
data['date'] = date;
data['text'] = text;
if (links != null) {
data['links'] = links!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Links {
String? link;
String? text;
Links({this.link, this.text});
Links.fromJson(Map<String, dynamic> json) {
link = json['link'];
text = json['text'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['link'] = link;
data['text'] = text;
return data;
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
//late Future<EngagementText> futureAlbumText;
List<Future<EngagementText>> futureAlbum = [];
@override
void initState() {
super.initState();
for (int index = 0; index < 5; index++) {
futureAlbum[index] = fetchAlbum();
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<EngagementText>(
future: futureAlbum[3], // referenced the array instead
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.text as String);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}