颤振:RangeError(索引):无效值:不在包含范围内0..27:28
Posted
技术标签:
【中文标题】颤振:RangeError(索引):无效值:不在包含范围内0..27:28【英文标题】:Flutter : RangeError (index): Invalid value: Not in inclusive range 0..27: 28 【发布时间】:2021-08-14 01:16:43 【问题描述】:大家好,我是颤振初学者,在练习滑动关闭选项时,我已经完成了下面提到的代码,删除一些产品后,我收到以下错误,我试图解决问题但不能,请提供给我您的宝贵建议。
下面我附上了代码和错误供您参考。
======== 小部件库捕获的异常=================================== ====================== 以下 RangeError 被抛出构建: RangeError(索引):无效值:不在包含范围 0..27:28
当异常被抛出时,这是堆栈: #0 列表。[] (dart:core-patch/growable_array.dart:254:60) #1 MyHome.build。 (包: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。 (包: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]"),
),
);
,
),
);
【问题讨论】:
【参考方案1】:我无法理解问题的原因,但我能够通过将 MyHome
小部件转换为 StatefulWidget
并在删除该项目时调用 setState
来修复它。
这是新代码:
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]"),
),
);
,
),
);
【讨论】:
已解决问题,感谢您的回复。以上是关于颤振:RangeError(索引):无效值:不在包含范围内0..27:28的主要内容,如果未能解决你的问题,请参考以下文章
RangeError(索引):无效值:不在 0..6 范围内,包括:-2
RangeError(索引):无效值:不在 0..7 范围内,包括:8
Flutter:RangeError(索引):无效值:不在0..14范围内,包括:15
Flutter - RangeError(索引):无效值:有效值范围为空:0