flutter - 颤动中的Text()小部件中的迭代列表抛出错误:RangeError(索引):无效值:有效值范围为空:0
问题描述
我想将用户提供的两个输入之间的所有自然数显示到 Text 小部件中,但出现上述错误。这是我的代码片段:
List<int> naturalNumber = []; <------Initialization of natural number(in the state class)
onPressed:(){
setState(() {
int X = int.parse(valueOfX.text);
int Y = int.parse(valueOfY.text);
difference = Y-X;
if(X>0 && Y>0 && Y-X>1 &&Y-X<50){
for(var i=0;i<=difference;i++){
naturalNumber[i] = X;
X=X+1;
}
for(int j=0;j<=naturalNumber.length;j++)
{
print(naturalNumber[j]);
}
shouldDisplay = !shouldDisplay;
}
}
}
在这里,我想打印用户输入之间的所有自然数:
shouldDisplay?Column(
children: [
for ( var i in naturalNumber ) Text(i.toString())
],
):Spacer()
解决方案
尝试使用以下代码:
import 'package:flutter/material.dart';
void main() =>
runApp(MaterialApp(home: CounterDemo()));
class CounterDemo extends StatefulWidget {
@override
_CounterDemoState createState() => _CounterDemoState();
}
class _CounterDemoState extends State<CounterDemo> {
var shouldDisplay = false;
int x = 20;
int y = 19;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Counter Demo"),
),
body: SingleChildScrollView(
child: Column(
children: [
RaisedButton(
child: const Text("Show Values"),
onPressed:()=>setState(() {
shouldDisplay = !shouldDisplay;
}),
),
shouldDisplay
? ListView.builder(
shrinkWrap: true,
itemCount: (x - y).abs() + 1,
itemBuilder: (BuildContext ctxt, int index) {
var highestValue =x>y?x:y;
var lowestValue =x<y?x:y;
// in ascending form from 1 to 10
return Center(child: Text((lowestValue + index).abs().toString()));
// in descending form from 10 to 1
// return Center(child: Text((highestValue - index).abs().toString()));
})
: Container(),
],
),
),
);
}
}
这对我有用。:)
推荐阅读
- python - 我正在尝试将 Twilio 广播 SMS 功能添加到我的 Django 应用程序,但无法弄清楚如何检索所有数据库电话号码
- java - 如何测试作业类引用是否属于特定类(JNI)
- arrays - 在 Swift 中解码没有键的 JSON 数组
- python - 使用 Cron Job 运行 python 程序
- apache-spark - 为什么我在运行 spark 作业时收到 java.net.SocketException
- python - 我如何使用 python 3 从 tkinter 窗口观看我的树莓派 picamera?
- security - CVE-2020-36328 关注 Centos 7 上的枕头使用 libwebp 0.3.0-3 吗?
- pine-script - strategy.entry 上的 Pine Script 版本 4 限制参数不运行
- javascript - 在打字稿的单行中从数组对象中获取特定值
- python - 如何使用作为 numpy 数组列的列上的条件来索引数据框?