RangeError (index): Invalid value: Only valid value is 0: 1, I get this error everytime i reload my screen

huangapple go评论126阅读模式
英文:

RangeError (index): Invalid value: Only valid value is 0: 1, I get this error everytime i reload my screen

问题

这是页面的整个代码,每当我重新加载页面时,都会在几秒钟内出现此错误,然后它会消失。我知道代码非常凌乱,对此我感到抱歉,但这个问题一直反复出现。

我认为在页面加载完成之前放置一个圆形进度指示器可能会解决问题,但不确定如何正确实现它,因为我不知道要检查哪个条件。

也许与它尝试在加载之前访问某些属性有关,因此问题可能通过检查“results”是否为空来解决。但不能这样做,因为它的作用域仅限于“fetchMyHome()”函数。我对Flutter相对较新,所以请帮助一下。

(请注意,您提到的特定问题或代码块没有提供详细的上下文,因此我无法提供针对该问题的具体建议。如果您需要关于如何实现进度指示器或处理特定问题的帮助,请提供更多的上下文和详细信息。)

Widget build(BuildContext context) {
  // Add a condition to check if data is loaded
  if (Name.isEmpty) {
    // Display a circular progress indicator while data is loading
    return Scaffold(
      body: Center(
        child: CircularProgressIndicator(),
      ),
    );
  } else {
    // Your existing code for displaying the page
    final now = DateTime.now().toLocal();
    final duration = launchTime.difference(now);
    // ...
  }
}

上面的代码片段演示了在数据加载完成之前显示圆形进度指示器的方式。它检查Name是否为空,如果为空,则显示进度指示器,一旦数据加载完成(Name 不再为空),就会显示页面的其余部分。您可以根据需要调整条件和显示进度指示器的方式。

英文:

This is the entire code of the page, whenever I reload the page I get this error for a few seconds and then it disappears. I know the code is very messy and I am sorry for that but this problem just keeps on coming again and again.

import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:space_flight_recorder/nav_bar/Nav_Drawer.dart';
import 'dart:convert';
import 'package:space_flight_recorder/nav_bar/bottom_nav_bar.dart';
class MyHome extends StatefulWidget {
const MyHome({Key? key}) : super(key: key);
@override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
DateTime launchTime = DateTime.now();
String Name='';
String description='';
String agencyName='';
String type = '';
String rocketName='';
String rocketVariant='';
String missionName='';
String orbitName='';
String location='';
String time='';
String date = '';
@override
void initState() {
super.initState();
fetchMyHome();
Timer.periodic(Duration(seconds: 1), (Timer t) => updateCountdown());
}
void fetchMyHome() async {
final response = await http.get(
Uri.parse('https://lldev.thespacedevs.com/2.2.0/launch/upcoming/')
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final List<dynamic> results = data['results'];
if (results.isNotEmpty) {
final launch = results.elementAt(0);
final launchTimeStr = launch['net'];
launchTime = DateTime.parse(launchTimeStr).toLocal();
final Launchname = launch['name'];
Name = Launchname.toString();
final descp = launch['mission']['description'];
description=descp;
final agenName=launch['launch_service_provider']['name'];
agencyName=agenName;
final typee=launch['launch_service_provider']['type'];
type=typee;
final r_name=launch['rocket']['configuration']['name'];
rocketName=r_name;
final r_variant=launch['rocket']['configuration']['variant'];
rocketVariant=r_variant;
final m_name=launch['mission']['name'];
missionName=m_name;
final orbit_name=launch['mission']['orbit']['name'];
orbitName=orbit_name;
final pad_location=launch['pad']['location']['name'];
location=pad_location;
final estimated_time=launch['net'];
time=estimated_time;
// final estimated_date=launch['pad']['location']['name'];
// date=estimated_date;
setState(() {});
} else {
print('No upcoming launches found');
}
} else {
print('Failed to fetch upcoming launches: ${response.statusCode}');
}
}
void updateCountdown() {
setState(() {});
}
@override
Widget build(BuildContext context) {
final now = DateTime.now().toLocal();
final duration = launchTime.difference(now);
final days = duration.inDays;
final hours = duration.inHours.remainder(24);
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
final final_time = time.split("T");
final date_final = final_time.elementAt(0).toString();
final time_final = final_time.elementAt(1).toString();
return Scaffold(
backgroundColor: Colors.black54,
drawer: Nav_Drawer(),
appBar: AppBar(
backgroundColor: Colors.black,
title: const Text('Welcome'),
),
body:
SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(height: 20),
Text(
'Next Launch in:',
style: TextStyle(
color: Colors.white,
fontSize: 24),
),
const SizedBox(height: 20),
Stack(
alignment: Alignment.center,
children: [
CarouselSlider(
items: [
Image.network('https://c4.wallpaperflare.com/wallpaper/559/511/583/spacex-rocket-falcon-9-smoke-wallpaper-preview.jpg'),
Image.network('https://c4.wallpaperflare.com/wallpaper/81/233/257/spacex-rocket-smoke-cape-canaveral-wallpaper-preview.jpg'),
Image.network('https://c4.wallpaperflare.com/wallpaper/758/798/536/spacex-rocket-launch-pads-falcon-heavy-wallpaper-preview.jpg'),
Image.network('https://cdnn1.img.sputniknews.com/img/07e6/0a/17/1102543952_0:0:3071:1728_1920x0_80_0_0_94bf3eb33e85402d96a49a4e84e93b84.jpg'),
Image.network('https://static.theprint.in/wp-content/uploads/2018/03/6-01-e1530068959485.jpg?compress=true&quality=80&w=376&dpr=2.6'),
Image.network('https://c4.wallpaperflare.com/wallpaper/390/31/781/spacex-rocket-falcon-9-wallpaper-preview.jpg'),
],
options: CarouselOptions(
height: 300,
// height: 200.0,
// enlargeCenterPage: true,
autoPlay: false,
enableInfiniteScroll: true,
autoPlayAnimationDuration: Duration(seconds: 3),
viewportFraction: 1,
),
),
Column(
children: [
Text(
'$days : $hours : $minutes : $seconds',
style: TextStyle(
fontSize: 30,
color: Colors.white
),
),
Text(
'Days : Hours : Minutes : Seconds',
style: TextStyle(
color: Colors.white,
fontSize: 12
),
),
],
),
],
),
Text(Name,
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
SizedBox(height: 20),
Padding(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(
color: Colors.white,
),
Text('Description:',
style: TextStyle(
color: Colors.blueAccent,
fontSize: 14
),
),
SizedBox(height: 4),
Text(description,
style: TextStyle(
color: Colors.white,
fontSize: 14
),),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Agency:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(agencyName,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Launch type:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(type,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Rocket name:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(rocketName,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Rocket variant:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(rocketVariant,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Mission Name:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(missionName,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
SizedBox(height: 5),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Orbit:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(orbitName,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Launch Location:',
style: TextStyle(
color: Colors.blueAccent,
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children:[
Text(location,
style: TextStyle(
color: Colors.white
),
),
Divider(
color: Colors.white,
)
],
),
Divider(
color: Colors.white,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Date:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(date_final,
style: TextStyle(
color: Colors.white
),
),
],
),
Divider(
color: Colors.white,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Time:',
style: TextStyle(
color: Colors.blueAccent,
),
),
Text(time_final,
style: TextStyle(
color: Colors.white
),
),
],
),
],
),
),
],
),
),
bottomNavigationBar: BottomNavBar(0),
);
}
}

I think putting a circular progress Indicator till the page loads might solve it but not sure how to implement it correctly as I don't know which condition to check.
Maybe it has something to do with the fact that it is trying to access some properties before they are loaded and hence the problem might be solved by checking if 'results' is empty or not. But can't do that because its scope is limited to the 'fetchMyHome()' function. I am relatively new to flutter so please help.

答案1

得分: 0

错误发生在您尝试访问列表中不存在的索引值时:

例如:

List list = ["a","b"];
list[4]; // <-- 由于列表中没有索引4处的元素,会引发范围错误,

我们的应用程序尝试使用不存在的索引4处的值。

解决方案:

尝试在使用列表的索引值的地方进行调试。

英文:

The Error occurs when you are trying to access the index value in the list which does not exist:

For example:


List list = ["a","b"];
list[4]; // <-- Range Error since there's no element at index 4 in the list,

our application tries to use value at index 4, which does not exist. 

**Solution:**

 Try to debug at a point where you are using the index value of a list.


</details>



# 答案2
**得分**: 0

以下是您提供的代码的翻译:

```dart
对于快速修复,我引入了两个变量 `loading`  `error`。

这是我的状态 `_MyHomeState` 的代码
```dart
class _MyHomeState extends State<MyHome> {
  bool loading = true; // 用于加载状态的引入
  String? error; // 用于处理错误情况的引入
  DateTime launchTime = DateTime.now();
  String Name = '';
  String description = '';
  String agencyName = '';
  String type = '';
  String rocketName = '';
  String rocketVariant = '';
  String missionName = '';
  String orbitName = '';
  String location = '';
  String time = '';
  String date = '';

  @override
  void initState() {
    super.initState();
    fetchMyHome();
    Timer.periodic(Duration(seconds: 1), (Timer t) => updateCountdown());
  }

  void fetchMyHome() async {
    final response = await http.get(
        Uri.parse('https://lldev.thespacedevs.com/2.2.0/launch/upcoming/')
    );
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final List<dynamic> results = data['results'];
      if (results.isNotEmpty) {
        final launch = results.elementAt(0);
        final launchTimeStr = launch['net'];
        launchTime = DateTime.parse(launchTimeStr).toLocal();
        final Launchname = launch['name'];
        Name = Launchname.toString();
        final descp = launch['mission']['description'];
        description = descp;
        final agenName = launch['launch_service_provider']['name'];
        agencyName = agenName;
        final typee = launch['launch_service_provider']['type'];
        type = typee;
        final r_name = launch['rocket']['configuration']['name'];
        rocketName = r_name;
        final r_variant = launch['rocket']['configuration']['variant'];
        rocketVariant = r_variant;
        final m_name = launch['mission']['name'];
        missionName = m_name;
        final orbit_name = launch['mission']['orbit']['name'];
        orbitName = orbit_name;
        final pad_location = launch['pad']['location']['name'];
        location = pad_location;
        final estimated_time = launch['net'];
        time = estimated_time;
        // final estimated_date=launch['pad']['location']['name'];
        // date=estimated_date;
      } else {
        error = '未找到即将发射的任务';
        print('未找到即将发射的任务');
      }
    } else {
      error = '无法获取即将发射的任务';
      print('无法获取即将发射的任务: ${response.statusCode}');
    }
    loading = false;
    setState(() {});
  }

  void updateCountdown() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (loading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator(),),);
    }
    if (error != null) {
      return Scaffold(body: Center(child: Text(error!),),);
    }
    final now = DateTime.now().toLocal();
    final duration = launchTime.difference(now);
    final days = duration.inDays;
    final hours = duration.inHours.remainder(24);
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);
    final final_time = time.split("T");
    final date_final = final_time.elementAt(0).toString();
    final time_final = final_time.elementAt(1).toString();
    return Scaffold(
      backgroundColor: Colors.black54,
      drawer: Nav_Drawer(),

      appBar: AppBar(

        backgroundColor: Colors.black,
        title: Text('欢迎'),
      ),
      body:
      SingleChildScrollView(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 20),
            Text(
              '下一次发射还剩:',
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 24),
            ),
            const SizedBox(height: 20),

            Stack(
              alignment: Alignment.center,
              children: [
                CarouselSlider(
                  items: [
                    Image.network(
                        'https://c4.wallpaperflare.com/wallpaper/559/511/583/spacex-rocket-falcon-9-smoke-wallpaper-preview.jpg'),
                    Image.network(
                        'https://c4.wallpaperflare.com/wallpaper/81/233/257/spacex-rocket-smoke-cape-canaveral-wallpaper-preview.jpg'),
                    Image.network(
                        'https://c4.wallpaperflare.com/wallpaper/758/798/536/spacex-rocket-launch-pads-falcon-heavy-wallpaper-preview.jpg'),
                    Image.network(
                        'https://cdnn1.img.sputniknews.com/img/07e6/0a/17/1102543952_0:0:3071:1728_1920x0_80_0_0_94bf3eb33e85402d96a49a4e84e93b84.jpg'),
                    Image.network(
                        'https://static.theprint.in/wp-content/uploads/2018/03/6-01-e1530068959485.jpg?compress=true&amp;quality=80&amp;w=376&amp;dpr=2.6'),
                    Image.network(
                        'https://c4.wallpaperflare.com/wallpaper/390/31/781/spacex-rocket-falcon-9-wallpaper-preview.jpg'),
                  ],
                  options: CarouselOptions(
                    height: 300,
                    // height: 200.0,
                    // enlargeCenterPage: true,
                    autoPlay: false,
                    enableInfiniteScroll: true,
                    autoPlayAnimationDuration: Duration(seconds: 3),
                    viewportFraction: 1,
                  ),
                ),
                Column(
                  children: [
                    Text(
                      '$days$hours$minutes$seconds 秒',
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white
                      ),
                    ),
                    Text(
                      '天 时 分 秒',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12
                      ),
                    ),
                  ],
                ),

              ],
            ),
            Text(Name,
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 20
              ),
            ),
            SizedBox(height: 20),
            Padding(
              padding: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Divider(
                    color: Colors.white,
                  ),
                  Text('描述:',
                    style: TextStyle(
                        color: Colors.blueAccent,
                        fontSize: 14
                    ),
                  ),

                  SizedBox(height: 4),
                  Text(description,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14
                    ),),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('机构:',
                        style: TextStyle(
                          color: Colors.blueAccent,


<details>
<summary>英文:</summary>

For the quick fix, I introduced two variables `loading` and `error`.

Here is my code for a state `_MyHomeState`
```dart
class _MyHomeState extends State&lt;MyHome&gt; {
  bool loading = true;//introduced for loading
  String? error;//introduced for handling error case
  DateTime launchTime = DateTime.now();
  String Name = &#39;&#39;;
  String description = &#39;&#39;;
  String agencyName = &#39;&#39;;
  String type = &#39;&#39;;
  String rocketName = &#39;&#39;;
  String rocketVariant = &#39;&#39;;
  String missionName = &#39;&#39;;
  String orbitName = &#39;&#39;;
  String location = &#39;&#39;;
  String time = &#39;&#39;;
  String date = &#39;&#39;;

  @override
  void initState() {
    super.initState();
    fetchMyHome();
    Timer.periodic(Duration(seconds: 1), (Timer t) =&gt; updateCountdown());
  }

  void fetchMyHome() async {
    final response = await http.get(
        Uri.parse(&#39;https://lldev.thespacedevs.com/2.2.0/launch/upcoming/&#39;)
    );
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      final List&lt;dynamic&gt; results = data[&#39;results&#39;];
      if (results.isNotEmpty) {
        final launch = results.elementAt(0);
        final launchTimeStr = launch[&#39;net&#39;];
        launchTime = DateTime.parse(launchTimeStr).toLocal();
        final Launchname = launch[&#39;name&#39;];
        Name = Launchname.toString();
        final descp = launch[&#39;mission&#39;][&#39;description&#39;];
        description = descp;
        final agenName = launch[&#39;launch_service_provider&#39;][&#39;name&#39;];
        agencyName = agenName;
        final typee = launch[&#39;launch_service_provider&#39;][&#39;type&#39;];
        type = typee;
        final r_name = launch[&#39;rocket&#39;][&#39;configuration&#39;][&#39;name&#39;];
        rocketName = r_name;
        final r_variant = launch[&#39;rocket&#39;][&#39;configuration&#39;][&#39;variant&#39;];
        rocketVariant = r_variant;
        final m_name = launch[&#39;mission&#39;][&#39;name&#39;];
        missionName = m_name;
        final orbit_name = launch[&#39;mission&#39;][&#39;orbit&#39;][&#39;name&#39;];
        orbitName = orbit_name;
        final pad_location = launch[&#39;pad&#39;][&#39;location&#39;][&#39;name&#39;];
        location = pad_location;
        final estimated_time = launch[&#39;net&#39;];
        time = estimated_time;
        // final estimated_date=launch[&#39;pad&#39;][&#39;location&#39;][&#39;name&#39;];
        // date=estimated_date;
      } else {
        error = &#39;No upcoming launches found&#39;;
        print(&#39;No upcoming launches found&#39;);
      }
    } else {
      error = &#39;Failed to fetch upcoming launches&#39;;
      print(&#39;Failed to fetch upcoming launches: ${response.statusCode}&#39;);
    }
    loading = false;
    setState(() {});
  }

  void updateCountdown() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (loading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator(),),);
    }
    if (error != null) {
      return Scaffold(body: Center(child: Text(error!),),);
    }
    final now = DateTime.now().toLocal();
    final duration = launchTime.difference(now);
    final days = duration.inDays;
    final hours = duration.inHours.remainder(24);
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);
    final final_time = time.split(&quot;T&quot;);
    final date_final = final_time.elementAt(0).toString();
    final time_final = final_time.elementAt(1).toString();
    return Scaffold(
      backgroundColor: Colors.black54,
      drawer: Nav_Drawer(),

      appBar: AppBar(

        backgroundColor: Colors.black,
        title: const Text(&#39;Welcome&#39;),
      ),
      body:
      SingleChildScrollView(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(height: 20),
            Text(
              &#39;Next Launch in:&#39;,
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 24),
            ),
            const SizedBox(height: 20),

            Stack(
              alignment: Alignment.center,
              children: [
                CarouselSlider(
                  items: [
                    Image.network(
                        &#39;https://c4.wallpaperflare.com/wallpaper/559/511/583/spacex-rocket-falcon-9-smoke-wallpaper-preview.jpg&#39;),
                    Image.network(
                        &#39;https://c4.wallpaperflare.com/wallpaper/81/233/257/spacex-rocket-smoke-cape-canaveral-wallpaper-preview.jpg&#39;),
                    Image.network(
                        &#39;https://c4.wallpaperflare.com/wallpaper/758/798/536/spacex-rocket-launch-pads-falcon-heavy-wallpaper-preview.jpg&#39;),
                    Image.network(
                        &#39;https://cdnn1.img.sputniknews.com/img/07e6/0a/17/1102543952_0:0:3071:1728_1920x0_80_0_0_94bf3eb33e85402d96a49a4e84e93b84.jpg&#39;),
                    Image.network(
                        &#39;https://static.theprint.in/wp-content/uploads/2018/03/6-01-e1530068959485.jpg?compress=true&amp;quality=80&amp;w=376&amp;dpr=2.6&#39;),
                    Image.network(
                        &#39;https://c4.wallpaperflare.com/wallpaper/390/31/781/spacex-rocket-falcon-9-wallpaper-preview.jpg&#39;),
                  ],
                  options: CarouselOptions(
                    height: 300,
                    // height: 200.0,
                    // enlargeCenterPage: true,
                    autoPlay: false,
                    enableInfiniteScroll: true,
                    autoPlayAnimationDuration: Duration(seconds: 3),
                    viewportFraction: 1,
                  ),
                ),
                Column(
                  children: [
                    Text(
                      &#39;$days : $hours : $minutes : $seconds&#39;,
                      style: TextStyle(
                          fontSize: 30,
                          color: Colors.white
                      ),
                    ),
                    Text(
                      &#39;Days : Hours : Minutes : Seconds&#39;,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 12
                      ),
                    ),
                  ],
                ),

              ],
            ),
            Text(Name,
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 20
              ),
            ),
            SizedBox(height: 20),
            Padding(
              padding: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Divider(
                    color: Colors.white,
                  ),
                  Text(&#39;Description:&#39;,
                    style: TextStyle(
                        color: Colors.blueAccent,
                        fontSize: 14
                    ),
                  ),

                  SizedBox(height: 4),
                  Text(description,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14
                    ),),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Agency:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(agencyName,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Launch type:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(type,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Rocket name:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(rocketName,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Rocket variant:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(rocketVariant,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Mission Name:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(missionName,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Orbit:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(orbitName,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Launch Location:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(location,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                      Divider(
                        color: Colors.white,
                      )
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Date:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(date_final,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.white,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(&#39;Time:&#39;,
                        style: TextStyle(
                          color: Colors.blueAccent,
                        ),
                      ),
                      Text(time_final,
                        style: TextStyle(
                            color: Colors.white
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

          ],
        ),
      ),
      bottomNavigationBar: BottomNavBar(0),
    );
  }
}

答案3

得分: 0

发生错误的情况是当您尝试访问列表中不存在的索引值时:

例如:

List list = ["a","b"];
list[4]; // &lt;-- 由于列表中没有索引4的元素,因此会出现范围错误,

我们的应用程序尝试使用不存在的索引4处的值。

解决方案:尝试在使用列表的索引值的地方进行调试。

如果您正在从API中获取数据,这是正确的做法:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Future fetchResult() async {
    final response = await http.get(
      Uri.parse('https://lldev.thespacedevs.com/2.2.0/launch/upcoming/');

    if(response.statusCode == 200){
      final apiData = jsonDecode(response.body);

      return apiData;
    }else{
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: Theme.of(context).textTheme.displayMedium!,
      textAlign: TextAlign.center,
      child: FutureBuilder(
        future: fetchResult(), // 先前获得的Future<String>或null
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          List<Widget> children;
          if (snapshot.hasData) {
            final List<dynamic> results = snapshot.data['results'];
            return  ListView.builder(
              itemCount: results.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  width: 100,
                  height: 100,
                  color: Colors.red,
                );
              },
            );
          } else if (snapshot.hasError) {
            children = <Widget>[
              const Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only top: 16),
                child: Text('Error: ${snapshot.error}'),
              ),
            ];
          } else {
            children = const <Widget>[
              SizedBox(
                width: 60,
                height: 60,
                child: CircularProgressIndicator(),
              ),
              Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text('Awaiting result...'),
              ),
            ];
          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: children,
            ),
          );
        },
      ),
    );
  }
}
英文:

The Error occurs when you are trying to access the index value in the list which does not exist:

For example:


List list = [&quot;a&quot;,&quot;b&quot;];
list[4]; // &lt;-- Range Error since there&#39;s no element at index 4 in the list,

our application tries to use value at index 4, which does not exist.

Solution: Try to debug at a point where you are using the index value of a list.

If you are fetching data from and API that's the correct way of doing it:


import &#39;package:flutter/material.dart&#39;;

void main() =&gt; runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const String _title = &#39;Flutter Code Sample&#39;;

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}



class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State&lt;MyStatefulWidget&gt; createState() =&gt; _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State&lt;MyStatefulWidget&gt; {
  Future fetchResult() async {
final response = await http.get(
      Uri.parse(&#39;https://lldev.thespacedevs.com/2.2.0/launch/upcoming/&#39;);

if(response.statusCode == 200){
 final apiData = jsonDecode(response.body);
     
    return apiData;

}else{
   return null;
}

}

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: Theme.of(context).textTheme.displayMedium!,
      textAlign: TextAlign.center,
      child: FutureBuilder(
        future: fetchResult(), // a previously-obtained Future&lt;String&gt; or null
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          List&lt;Widget&gt; children;
          if (snapshot.hasData) {
           final List&lt;dynamic&gt; results = snapshot.data[&#39;results&#39;];
 return  ListView.builder(
             itemCount: results.length,
            itemBuilder: (BuildContext context, int index) {
            return Container(
              width: 100,
              height: 100,
              color: Colors.red,
            );
            },
            );
          } else if (snapshot.hasError) {
            children = &lt;Widget&gt;[
              const Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text(&#39;Error: ${snapshot.error}&#39;),
              ),
            ];
          } else {
            children = const &lt;Widget&gt;[
              SizedBox(
                width: 60,
                height: 60,
                child: CircularProgressIndicator(),
              ),
              Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text(&#39;Awaiting result...&#39;),
              ),
            ];
          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: children,
            ),
          );
        },
      ),
    );
  }
}





</details>



huangapple
  • 本文由 发表于 2023年2月19日 12:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定