我想将用户提供的两个输入之间的所有自然数显示到“文本”小部件中,但出现上述错误。这是我的代码片段:

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

这对我有用。 :)

关于flutter - flutter 中引发Text()小部件中的迭代列表抛出错误:RangeError(索引):无效值:有效值范围为空:0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62277781/

10-10 19:48