首页 > 解决方案 > Flutter - RangeError(索引):无效值:有效值范围为空:0

问题描述

我想构建一个测验应用程序,如下图所示

在此处输入图像描述

但我得到了那个错误,那是因为组值的索引。我是颤振和编码的新手,所以请帮助我。我不知道如何解决它。

class _ReadingPage2State extends State<ReadingPage2> {
  bool _isloading = false;
  List<int> groupValue = [];
  List<List<int>> value = [];
  int questionId;

  Future<Response> loadQuestion() async {
    final url = Network().link('/exercise/1/questions');
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    final token = jsonDecode(localStorage.getString('token'));
    http.Response response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    });
    if (response.statusCode == 200) {
      var jsonResponce = response.body;
      Response res = Response.fromJson(json.decode(jsonResponce));
      return res;
    } else
      throw Exception('Failed to load Question');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Set 1"),
        backgroundColor: Colors.orange,
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: FutureBuilder<Response>(
                future: loadQuestion(),
                builder: (context, AsyncSnapshot<Response> snapshot) {
                  if (snapshot.hasData) {
                    List<Result> list = snapshot.data.result;
                    return ListView.builder(
                      itemCount: list.length + 1,
                      itemBuilder: (context, index) => index < list.length
                          ?
                          Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                Container(
                                  child: Column(
                                    children: <Widget>[
                                      Text(
                                        snapshot
                                            .data.result[index].questionText,
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontSize: 20.0,
                                            fontWeight: FontWeight.w600),
                                      ),
                                      Container(
                                        width: 150,
                                        child: Row(
                                          children: <Widget>[
                                            Radio(
                                                value: snapshot
                                                    .data
                                                    .result[index]
                                                    .options[0]
                                                    .id,
                                                groupValue: groupValue[index],
                                                onChanged: (value) {
                                                  setState(() {
                                                    groupValue[index] = value;
                                                    print(groupValue[index]);
                                                  });
                                                }),
                                            Text(
                                                snapshot.data.result[index]
                                                    .options[0].option,
                                                style: TextStyle(fontSize: 20)),
                                          ],
                                        ),
                                      ),
                                      Container(
                                        width: 150,
                                        child: Row(
                                          children: <Widget>[
                                            Radio(
                                                value: snapshot
                                                    .data
                                                    .result[index]
                                                    .options[1]
                                                    .id,
                                                groupValue: groupValue[index],
                                                onChanged: (value) {
                                                  setState(() {
                                                    groupValue[index] = value;
                                                    print(groupValue[index]);
                                                  });
                                                }),
                                            Text(
                                                snapshot.data.result[index]
                                                    .options[1].option,
                                                style: TextStyle(fontSize: 20)),
                                          ],
                                        ),
                                      ),
                                      SizedBox(height: 25),
                                    ],
                                  ),
                                ),
                              ],
                            )
                          : MaterialButton(
                              minWidth: double.infinity,
                              height: 40,
                              onPressed: () {
                                saveAnswer(questionId, groupValue[index]);
                              },
                              color: Color(0xFFFF9D00),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50),
                              ),
                              child: Text('Submit'),
                            ),
                    );
                  } else if (snapshot.hasError) {
                    debugPrint("${snapshot.error}");
                    return Text("${snapshot.error}",
                        style: TextStyle(fontSize: 15));
                  }
                  return Center(child: CircularProgressIndicator());
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

如果我将默认值设置为组值,就可以了,并且可以显示问题。但我不想为其设置默认值。

标签: flutterlistviewradio-buttonflutter-futurebuilder

解决方案


您正在从列表进行迭代,并且列表确实从 0 开始索引,

所以,改变

 itemCount: list.length + 1,

 itemCount: list.length,

推荐阅读