简体   繁体   中英

RangeError (index): Invalid value: Not in range 0..3, inclusive: 4 in Flutter

I am getting a range error while running my code. I just want to show the items on my home screen but it is showing an error. Please help me. Thank you very much in advance. I don't know where I am getting this error. Here is my error output.

 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) ...

Here is My Code

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

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

I found a trick that works for me, when facing the RangeError (index) error: Invalid value: Not in range 0..3, inclusive: 4 in Flutter.

Apparently it happens that the scrolling attached to the listview goes too fast to the point of exceeding the length of the array by one unit.

First I add itemCount: items.length, then in itemBuilder and before the return I insert this: if (index> = items.length) {return const Offstage (); }

A complete example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM