RangeError(索引):无效值:不在0..3范围内,包括:Flutter中为4

时间:2020-09-14 23:26:18

标签: android flutter dart flutter-layout

运行代码时出现范围错误。 我只想在主屏幕上显示项目,但显示错误。请帮我。提前非常感谢您。我不知道我在哪里得到这个错误。这是我的错误输出。

Exception caught by widgets library ═══════════════════════════════════════════════════════
The following RangeError was thrown building HomeScreen(dirty, dependencies: [MediaQuery, _InheritedTheme, _LocalizationsScope-[GlobalKey#4b453]]):
RangeError (index): Invalid value: Not in range 0..3, inclusive: 4

The relevant error-causing widget was: 
  HomeScreen file:///C:/Project/ur_info/lib/WelcomeScreen/WelcomeScreen.dart:56:45
When the exception was thrown, this was the stack: 
#0      List.[] (dart:core-patch/growable_array.dart:146:60)
#1      HomeScreen.build (package:urinfo/Home/home.dart:72:45)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4576:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
...

这是我的代码

Home.Dart

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:urinfo/Home/items.dart';

import 'Events.dart';
import 'categories.dart';

class HomeScreen extends StatelessWidget {
  final url;
  final Events events;

  const HomeScreen({Key key, this.url, this.events}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.pink[50],
        body: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              color: Colors.pink[50]
            ),
            child: Padding(
              padding: EdgeInsets.only(left: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: size.height*0.05 ),
                  Center(
                    child: RichText(
                      text: TextSpan(
                        style: Theme.of(context).textTheme.headline5,
                        children: [
                          TextSpan(text: "Hello Welcome Back Pratul", style: TextStyle(fontWeight: FontWeight.bold))
                        ]
                      ),
                    ),
                  ),
                  SizedBox(height: 10),
                  Center(child: Text("Categories", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.indigo),)),
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Padding(
                      padding: EdgeInsets.only(top: 10),
                      child: Row(
                        children: <Widget>[
                          Categories (
                            name: "Btech", imageurl: "assets/icons/Btech.svg",),
                          Categories (
                            name: "BA Hons.", imageurl: "assets/icons/Bahons.svg",),
                          Categories (
                            name: "Pharmacy", imageurl: "assets/icons/nursing.svg",),

                          Categories (
                            name: "Business", imageurl: "assets/icons/Business.svg",),

                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: size.height*.12,),
                  Center(child: Text("Upcomming Events", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.indigo),)),
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Padding(
                      padding: const EdgeInsets.only(top: 15, right: 10),
                      child: Row(
                        children: <Widget>[
                          Events(item: items[items.length]),
                          SizedBox(width: 15)],
                      ),
                    ),
                  )

                ],
              ),
            ),
          ),
        ),

        ),
    );
  }
}

Events.Dart

import 'package:flutter/material.dart';
import 'package:urinfo/webview.dart';

import 'items.dart';

class Events extends StatelessWidget {
final Item item;

  const Events({Key key, this.item}) : super(key: key);
@override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Navigator.push(context, MaterialPageRoute(builder: (context)=> Webview()));
      },
      child: Container(
        width: 120,
        height: 170,
        child: Stack(
          children: <Widget>[
            Container(
              height: 150,
              decoration: BoxDecoration(
                  color: item.color,
                  borderRadius: BorderRadius.circular(20)
              ),

            ),
            Column(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.only(top: 5, left: 5, right: 5),
                    child: Image.asset(item.imageurl, fit: BoxFit.cover, width: 100,),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Center(child: Text(item.name, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.white),)),
                )
              ],
            ),
          ],
        ),
      ),
    );

  }
}

Items.dart

import 'package:flutter/material.dart';

class Item {
  final String imageurl, name, weburl;
  final int id;
  final Color color;

  Item({this.color, this.imageurl, this.name, this.weburl, this.id});
}
List<Item> items=[
  Item(
    id: 0,
    imageurl: "assets/images/Dexterix.jpg",
    name: "Dexterix",
    weburl: "https://dexterix.tech/",
    color: Colors.black,

  ),
  Item(
    id: 1,
    imageurl: "assets/images/space apps.jpg",
    name: "Space Apps",
    weburl: "https://dexterix.tech/",
    color: Colors.black,

  ),
  Item(
    id: 2,
    imageurl:"assets/images/books.jpg",
    name: "Books Show",
    weburl: "https://dexterix.tech/",
    color: Colors.yellow[200],

  ),
  Item(
    id: 3,
    imageurl: "assets/images/SIH.png",
    name: "SIH",
    weburl: "https://dexterix.tech/",
    color: Colors.white10,

  ),
];

WelcomeScreen.dart

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:introduction_screen/introduction_screen.dart';

import '../Home/home.dart';

class WelcomeScreen extends StatefulWidget {
  @override
  _WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {
  List<PageViewModel> getPages() {
    return [
      PageViewModel(
          image: Image.asset("assets/images/Welcom.png"),
          title: ('Welcome To Ur Info'),
          body: "Your Own Info App",
          footer: Text("Lets Get Started"),
          decoration: PageDecoration(pageColor: Colors.lightBlue[50])
      ),
      PageViewModel(
          image: Image.asset("assets/images/Exams.png"),
          title: ('Get Your Exams Details'),
          body: "Download your admit cards & other details",
          footer: Text(""),
          decoration: PageDecoration(pageColor: Colors.green[100])

      ), PageViewModel(
          image: Image.asset("assets/images/Events.png"),
          title: ('Track all the upcomming Events'),
          body: "No need to worry about events",
          footer: Text(""),
          decoration: PageDecoration(pageColor: Colors.yellow[50])

      ), PageViewModel(
        image: Image.asset("assets/images/study.png"),
        title: ('Daily Feeds on Exams & Syllabus'),
        body: "Provides daily news related to education",
        footer: Text(""),

      ),
    ];
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          body: IntroductionScreen(
            globalBackgroundColor: Colors.pink[50],
            pages: getPages(),
            onSkip: (){
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => HomeScreen()
                  ));
            },
            onDone: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => HomeScreen()
                  ));
            },
            showSkipButton: true,
            showNextButton: true,
            dotsDecorator: DotsDecorator(
              color: Colors.pink,
              activeColor: Colors.blueAccent[700],
            ),
            dotsFlex: 1,
            skip: Text('Skip'),
            next: Text('Next'),
            done: Text('Get Started'),
          )

      ),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

items.length == 4,而列表始终从索引0开始。因此,它将尝试查找索引1到索引4的项目。我建议使用items.length-1。

答案 1 :(得分:0)

当我遇到 RangeError(索引)错误时,我发现了一个对我有用的技巧:无效值:不在范围 0..3,包括:4 在 Flutter 中。

显然,附加到列表视图的滚动发生得太快,以至于超出数组长度一个单位。

首先我添加 itemCount: items.length,然后在 itemBuilder 和 return 之前我插入这个: if (index> = items.length) {return const Offstage (); }

一个完整的例子:

DisplayItemsList () Widget {
    final widget = ListView.builder (
      physics: ScrollPhysics (),
      reverse: reverse,
      shrinkWrap: true,
      controller: scrollControllerClientsList,
      itemCount:items.length,
      itemBuilder: (_, index) {
        log ('displayItemsList: itemBuilder: index: $ index');
        if (index> = items.length) {
          return const Offstage ();
        }
        return displayOneOiLine (index);
          },
    );