Hello Everyone I am flutter beginner and while practicing the Swipe to dismiss option I have completed the below mentioned code and after deleting few Products I am receiving the below error, I tried to solve the problem but couldn't, Kindly provide me your valuable suggestions.
Below I have Attached the code and error for your reference.
======== Exception caught by widgets library ======================================================= The following RangeError was thrown building: RangeError (index): Invalid value: Not in inclusive range 0..27: 28
When the exception was thrown, this was the stack: #0 List.[] (dart:core-patch/growable_array.dart:254:60) #1 MyHome.build. (package:flutterswipedismiss/main.dart:34:27) #2 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22) #3 SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1201:28) #4 SliverMultiBoxAdaptorElement.createChild. (package:flutter/src/widgets/sliver.dart:1214:55) ...
Main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
final List<String> items =
List<String>.generate(30, (i) => "Product ${i + 1}");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Delete panna sidela thallu"),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, int index) {
return Dismissible(
key: Key(items[index]),
onDismissed: (direction) {
items.removeAt(index);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Item Dismissed."),
),
);
},
background: Container(
color: Colors.red,
),
child: ListTile(
title: Text("${items[index]}"),
),
);
},
),
);
}
}
I could not understand the cause of the problem, but i was able to fix it by converting the MyHome
widget to StatefulWidget
, and calling setState
on removing the item.
here is the new code:
class MyHome extends StatefulWidget {
@override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
final List<String> items =
List<String>.generate(30, (i) => "Product ${i + 1}");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Delete panna sidela thallu"),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, int index) {
return Dismissible(
key: Key(items[index]),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Item Dismissed."),
),
);
},
background: Container(
color: Colors.red,
),
child: ListTile(
title: Text("${items[index]}"),
),
);
},
),
);
}
}