0
  1. 我正在从 API 中提取测验数据,并使用 StreamBuilder
  2. 使用 PageView.builder 在单独的页面中显示每个问题和选项
  3. RadioListTile 用于选项并使用地图从列表中迭代答案

问题是--> 每当我在任何问题中选择任何选项时,问题都会自动更改,但索引不会,并且我无法在任何问题上选择任何选项。

我希望我能够很好地解释我的问题。

附加 JSON、PageView.Builder 代码。

页面视图控制器

 PageController _pageViewController = PageController(initialPage: 0);

  var currentPageIndex;
  getCurrectPageIndex(index) {
    setState(() {
      currentPageIndex = index;
    });
  }

页面视图按钮

pageViewButtons(context, questionDataIndex, snapshotData, _pageViewController) {
  bool isLastQues = questionDataIndex == snapshotData.last;
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: [
      circularButton(
        text: "Previous",
        onPressed: () {
          _pageViewController.previousPage(
              duration: Duration(microseconds: 100), curve: Curves.ease);
        },
        color: brandBlue,
      ),
      circularButton(
        text: isLastQues ? "Finish" : "Next",
        onPressed: (isLastQues)
            ? () {
                showDialogBox(
                  context: context,
                  headingText: "Submit all answers?",
                  contentText:
                      "Press Submit to submit answers or Dismiss to cancel",
                  widget: ElevatedButton(
                    child: Text("Submit"),
                    onPressed: questionDataIndex == snapshotData.last
                        ? () => Get.off(() => ResultView())
                        : null,
                  ),
                );
              }
            : () => _pageViewController.nextPage(
                duration: Duration(microseconds: 100), curve: Curves.ease),
        color: brandRed,
      ),
    ],
  );
}

ElevatedButton circularButton(
    {String? text, Function()? onPressed, Color? color}) {
  return ElevatedButton(
    child: Text(text!),
    onPressed: onPressed,
    style: ButtonStyle(
      backgroundColor: MaterialStateProperty.all<Color>(color!),
      shape: MaterialStateProperty.all<OutlinedBorder?>(
        RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
      ),
    ),
  );
}

分页码

_pagination(List<Response> snapshotData) {
return new Container(
  width: deviceSize.width * 0.90,
  height: deviceSize.height * 0.10,
  child: GridView.builder(
    itemCount: snapshotData.length,
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 5,
      childAspectRatio: 5 / 2,
      mainAxisSpacing: 10,
    ),
    itemBuilder: (context, index) {
      final indexValue = index;
      final indexValuePlus1 = (index + 1).toString();
      bool isEqual = indexValue == currentPageIndex;
      return Container(
        decoration: BoxDecoration(shape: BoxShape.circle),
        margin: EdgeInsets.symmetric(horizontal: 5),
        child: Material(
          shape: CircleBorder(),
          clipBehavior: Clip.hardEdge,
          color: Colors.white,
          child: InkWell(
            child: CircleAvatar(
              backgroundColor: () {
                if (isEqual) {
                  return brandRed;
                } else {
                  return brandBlue;
                }
              }(),
              child: Padding(
                padding: const EdgeInsets.all(2.0),
                child: CircleAvatar(
                  child: Text(
                    indexValuePlus1,
                    style: TextStyle(color: Colors.black87, height: 1.2),
                  ),
                  backgroundColor: Colors.white,
                ),
              ),
            ),
            onTap: () {
              _pageViewController.jumpToPage(indexValue);
            },
          ),
        ),
      );
    },
  ),
);}

PageView.Builder

_pageView(List<Response> snapshotData, ThemeData themeContext) {
return PageView.builder(
  controller: _pageViewController,
  physics: NeverScrollableScrollPhysics(),
  itemCount: snapshotData.length,
  onPageChanged: getCurrectPageIndex,
  itemBuilder: (context, index) {
    questionDataIndex = snapshotData[index];
    final questionTitle = questionDataIndex.title;
    final questionAnswers = questionDataIndex.answer;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _pagination(snapshotData),
        SizedBox(height: 20),
        Expanded(
          child: Stack(
            alignment: AlignmentDirectional.topCenter,
            clipBehavior: Clip.none,
            children: [
              Padding(
                padding: kDefaultPadding,
                child: Wrap(
                  children: [
                    Text(questionTitle.inCaps,
                        style: themeContext.textTheme.headline6!
                            .copyWith(fontWeight: FontWeight.bold)),
                    SizedBox(width: 20, height: 20),
                    ...questionAnswers.map((answer) {
                      return RadioListTile(
                        key: new Key(answer.id.toString()),
                        dense: true,
                        title: Text(
                          answer.answerText.inCaps,
                          style: themeContext.textTheme.bodyText2,
                        ),
                        value: answer.id,
                        groupValue: groupValue,
                        onChanged: (value) {
                          setState(() {
                            // groupValue = answer.id;
                            value = groupValue;
                          });
                        },
                      );
                    }).toList(),
                  ],
                ),
              )
            ],
          ),
        ),
      ],
    );
  },
);}

和 JSON

{
"status": "success",
"response": [
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 20,
        "title": "node.next -> node.next.next; will make",
        "answer": [
            {
                "id": 26,
                "answer_text": "node.next inaccessible"
            },
            {
                "id": 27,
                "answer_text": "node.next.next inaccessible"
            },
            {
                "id": 28,
                "answer_text": "this node inaccessible"
            },
            {
                "id": 29,
                "answer_text": "none of the above!"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 15,
        "title": "For a binary search algorithm to work, it is necessary that the array (list) must be",
        "answer": [
            {
                "id": 8,
                "answer_text": "sorted"
            },
            {
                "id": 9,
                "answer_text": "Unsorted"
            },
            {
                "id": 10,
                "answer_text": "In a heap"
            },
            {
                "id": 11,
                "answer_text": "popped out of stack"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 22,
        "title": "A pivot element to partition unsorted list is used in",
        "answer": [
            {
                "id": 34,
                "answer_text": "Merge Sort"
            },
            {
                "id": 35,
                "answer_text": "Quick Sort"
            },
            {
                "id": 36,
                "answer_text": "Insertion Sort"
            },
            {
                "id": 37,
                "answer_text": "Selection Sort"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 17,
        "title": "Find the odd out",
        "answer": [
            {
                "id": 14,
                "answer_text": "Prim's Minimal Spanning Tree Algorithm"
            },
            {
                "id": 15,
                "answer_text": "Kruskal's Minimal Spanning Tree Algorithm"
            },
            {
                "id": 16,
                "answer_text": "Floyd-Warshall's All pair shortest path Algorithm"
            },
            {
                "id": 17,
                "answer_text": "Dijkstra's Minimal Spanning Tree Algorithm"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 23,
        "title": "Apriori analysis of an algorithm assumes that −&quot;,
        "answer": [
            {
                "id": 38,
                "answer_text": "the algorithm has been tested before in real environment."
            },
            {
                "id": 39,
                "answer_text": "all other factors like CPU speed are constant and have no effect on implementation."
            },
            {
                "id": 40,
                "answer_text": "the algorithm needs not to be practical."
            },
            {
                "id": 41,
                "answer_text": "none of the above."
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 16,
        "title": "Postfix expression is just a reverse of prefix expression.",
        "answer": [
            {
                "id": 12,
                "answer_text": "Yes"
            },
            {
                "id": 13,
                "answer_text": "No"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 18,
        "title": "If the array is already sorted, which of these algorithms will exhibit the best performance",
        "answer": [
            {
                "id": 18,
                "answer_text": "Merge Sort"
            },
            {
                "id": 19,
                "answer_text": "Insertion Sort"
            },
            {
                "id": 20,
                "answer_text": "Quick Sort"
            },
            {
                "id": 21,
                "answer_text": "Heap Sort"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 21,
        "title": "Which of the following algorithm cannot be desiged without recursion −&quot;,
        "answer": [
            {
                "id": 30,
                "answer_text": "Tower of Hanoi"
            },
            {
                "id": 31,
                "answer_text": "Fibonacci Series"
            },
            {
                "id": 32,
                "answer_text": "Tree Traversal"
            },
            {
                "id": 33,
                "answer_text": "None of the above"
            }
        ]
    },
    {
        "question_type": "Multiple Choice",
        "difficulty": "Fundamental",
        "id": 19,
        "title": "Apriory algorithm analysis does not include −&quot;,
        "answer": [
            {
                "id": 22,
                "answer_text": "It is the easiest possible way."
            },
            {
                "id": 23,
                "answer_text": "To make sure that it is still complete binary tree."
            },
            {
                "id": 24,
                "answer_text": "Because left and right subtree might be missing."
            },
            {
                "id": 25,
                "answer_text": "None of the above!"
            }
        ]
    }
]}

问题更改问题可以在这里看到

4

1 回答 1

0

嘿,我不明白你的代码,但这是我所管理的:

import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  @override
  _TestScreenState createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  PageController controller = PageController();
  int index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('Quiz'),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            Container(
              height: 105,
              child: GridView(
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 5,
                  childAspectRatio: 3 / 2,
                  mainAxisSpacing: 10,
                ),
                children: List.generate(
                  questions.length,
                  (index) => Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color:
                            this.index == index ? Colors.red : Colors.lightBlue,
                        width: 2,
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '${index + 1}',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 15,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(height: 10),
            Expanded(
              child: Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Column(
                  children: [
                    Expanded(
                      child: PageView(
                        controller: controller,
                        physics: NeverScrollableScrollPhysics(),
                        children: List.generate(
                          questions.length,
                          (index) => Container(
                            padding: EdgeInsets.all(20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  questions[index]['title'],
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(height: 10),
                                // questions[index]['title'].forEach().
                                // questions.forEach((element) { }).toList
                                Expanded(
                                  child: Column(
                                    children: questions[index]['answer']
                                        .map<Widget>(
                                          (answer) => Container(
                                            child: ListTile(
                                              onTap: () {
                                                nextPage();
                                              },
                                              leading: Icon(Icons
                                                  .radio_button_off_rounded),
                                              title: Text(
                                                answer['answer_text'],
                                              ),
                                            ),
                                          ),
                                        )
                                        .toList(),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          ElevatedButton(
                            style: ButtonStyle(
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30),
                                ),
                              ),
                              padding: MaterialStateProperty.all(
                                EdgeInsets.symmetric(
                                  horizontal: 20,
                                  vertical: 12,
                                ),
                              ),
                            ),
                            onPressed: () {
                              previousPage();
                            },
                            child: Text(
                              'Previous',
                              style: TextStyle(fontSize: 14),
                            ),
                          ),
                          ElevatedButton(
                            style: ButtonStyle(
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(30),
                                ),
                              ),
                              padding: MaterialStateProperty.all(
                                EdgeInsets.symmetric(
                                  horizontal: 20,
                                  vertical: 12,
                                ),
                              ),
                              backgroundColor: MaterialStateProperty.all(
                                Colors.red[600],
                              ),
                            ),
                            onPressed: () {
                              nextPage();
                            },
                            child: Text(
                              'Next',
                              style: TextStyle(fontSize: 14),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 10),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void nextPage() {
    if (index < 9) {
      setState(() {
        index++;
      });
      controller.jumpToPage(index);
      print(index);
    } else {
      Navigator.of(context).pop();
    }
  }

  void previousPage() {
    if (index > 0) {
      setState(() {
        index--;
      });
      controller.jumpToPage(index);
      print(index);
    }
  }

  final List<Map<String, dynamic>> questions = [
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 20,
      "title": "node.next -> node.next.next; will make",
      "answer": [
        {"id": 26, "answer_text": "node.next inaccessible"},
        {"id": 27, "answer_text": "node.next.next inaccessible"},
        {"id": 28, "answer_text": "this node inaccessible"},
        {"id": 29, "answer_text": "none of the above!"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 15,
      "title":
          "For a binary search algorithm to work, it is necessary that the array (list) must be",
      "answer": [
        {"id": 8, "answer_text": "sorted"},
        {"id": 9, "answer_text": "Unsorted"},
        {"id": 10, "answer_text": "In a heap"},
        {"id": 11, "answer_text": "popped out of stack"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 22,
      "title": "A pivot element to partition unsorted list is used in",
      "answer": [
        {"id": 34, "answer_text": "Merge Sort"},
        {"id": 35, "answer_text": "Quick Sort"},
        {"id": 36, "answer_text": "Insertion Sort"},
        {"id": 37, "answer_text": "Selection Sort"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 17,
      "title": "Find the odd out",
      "answer": [
        {"id": 14, "answer_text": "Prim's Minimal Spanning Tree Algorithm"},
        {"id": 15, "answer_text": "Kruskal's Minimal Spanning Tree Algorithm"},
        {
          "id": 16,
          "answer_text": "Floyd-Warshall's All pair shortest path Algorithm"
        },
        {"id": 17, "answer_text": "Dijkstra's Minimal Spanning Tree Algorithm"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 23,
      "title": "Apriori analysis of an algorithm assumes that −&quot;,
      "answer": [
        {
          "id": 38,
          "answer_text":
              "the algorithm has been tested before in real environment."
        },
        {
          "id": 39,
          "answer_text":
              "all other factors like CPU speed are constant and have no effect on implementation."
        },
        {"id": 40, "answer_text": "the algorithm needs not to be practical."},
        {"id": 41, "answer_text": "none of the above."}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 16,
      "title": "Postfix expression is just a reverse of prefix expression.",
      "answer": [
        {"id": 12, "answer_text": "Yes"},
        {"id": 13, "answer_text": "No"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 18,
      "title":
          "If the array is already sorted, which of these algorithms will exhibit the best performance",
      "answer": [
        {"id": 18, "answer_text": "Merge Sort"},
        {"id": 19, "answer_text": "Insertion Sort"},
        {"id": 20, "answer_text": "Quick Sort"},
        {"id": 21, "answer_text": "Heap Sort"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 21,
      "title":
          "Which of the following algorithm cannot be desiged without recursion −&quot;,
      "answer": [
        {"id": 30, "answer_text": "Tower of Hanoi"},
        {"id": 31, "answer_text": "Fibonacci Series"},
        {"id": 32, "answer_text": "Tree Traversal"},
        {"id": 33, "answer_text": "None of the above"}
      ]
    },
    {
      "question_type": "Multiple Choice",
      "difficulty": "Fundamental",
      "id": 19,
      "title": "Apriory algorithm analysis does not include −&quot;,
      "answer": [
        {"id": 22, "answer_text": "It is the easiest possible way."},
        {
          "id": 23,
          "answer_text": "To make sure that it is still complete binary tree."
        },
        {
          "id": 24,
          "answer_text": "Because left and right subtree might be missing."
        },
        {"id": 25, "answer_text": "None of the above!"}
      ]
    }
  ];
}

阅读它,您可能会了解如何修改自己的代码以使其正常工作。

于 2021-08-11T09:16:37.047 回答