如何将Flutter中的Album示例更改为Albums列表

问题描述 投票:0回答:1

我对 Flutter 相当陌生,正在将 React Native 应用程序转换为 Flutter。我正在努力使用 flutter 文档中的一个示例来从云中读取 json 文件。

https://docs.flutter.dev/cookbook/networking/fetch-data

在我的应用程序中,我想读取“专辑”列表,如示例代码中所示。但似乎无论我尝试什么,我都会遇到不同的错误。这是我最接近让它发挥作用的一次。基本上它与专辑示例相同,只是我将其设为专辑列表,我使用 JSON 文件和类来解码 JSON。

当我运行它时,在第 96 行

List<Future<EngagementText>> futureAlbum = [];
我得到:

发生异常。
RangeError(RangeError(索引):无效值:有效值范围为空:0)

我尝试了很多方法,但根据我采取的所有不同方法,仍然出现不同的错误。

这是代码:

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();
            },
          ),
        ),
      ),
    );
  }
}
flutter dart
1个回答
0
投票

为何上榜<"Future" ? I don't understand why do you want use the "Future".

好主意 - 使用 DIO 连接互联网。

© www.soinside.com 2019 - 2024. All rights reserved.