flutter 范围错误(索引):无效值:唯一有效值为0:1,我得到这个错误每次我重新加载我的屏幕

vd8tlhqk  于 2023-02-20  发布在  Flutter
关注(0)|答案(3)|浏览(177)

这是整个页面的代码,每当我重新加载页面时,我会得到这个错误几秒钟,然后它消失了。我知道代码很乱,我很抱歉,但这个问题只是不断来一次又一次。

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),
    );
  }
}

我认为在页面加载之前放置一个循环进度指示器可能会解决这个问题,但不确定如何正确实现它,因为我不知道要检查哪个条件。也许这与它试图在加载之前访问一些属性有关,因此问题可能会通过检查“results”是否为空来解决。但不能这样做,因为它的范围限于"fetchMyHome()'函数。我对flutter比较陌生,所以请帮助。

sr4lhrrt

sr4lhrrt1#

为了快速修复,我引入了两个变量loadingerror
下面是状态_MyHomeState的代码

class _MyHomeState extends State<MyHome> {
  bool loading = true;//introduced for loading
  String? error;//introduced for handling error case
  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 = 'No upcoming launches found';
        print('No upcoming launches found');
      }
    } else {
      error = 'Failed to fetch upcoming launches';
      print('Failed to fetch upcoming launches: ${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: 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),
    );
  }
}
h5qlskok

h5qlskok2#

当您尝试访问列表中不存在的索引值时,会出现此错误:

例如:

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.
8zzbczxx

8zzbczxx3#

当您尝试访问列表中不存在的索引值时,会出现此错误:

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

我们的应用程序尝试使用索引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(), // a previously-obtained Future<String> or 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,
            ),
          );
        },
      ),
    );
  }
}

相关问题