简体   繁体   English

如何管理 listview.builder 中的控制器列表,这取决于 listView.builder 用于迭代的不同列表

[英]How to manage list of controllers inside listview.builder which depends on a different list the listView.builder uses to iterate

image图片

I have list of objects (Question).我有对象列表(问题)。 I'm iterating over inside ListView.builder.我在 ListView.builder 中进行迭代。

I have another list of objects (QuizQuestion) which from every QuizQuestion object I need a propery (ueserAnswer) for the user to change (that's why the TextFormField) so I can save and work with after that.我有另一个对象列表(QuizQuestion),从每个 QuizQuestion 对象中我需要一个属性(ueserAnswer)供用户更改(这就是 TextFormField 的原因),以便我可以在此之后保存和使用。

My main problem is the controller of textFormField and how to get the value.我的主要问题是 textFormField 的controller以及如何获取值。

This code results in 5 objects of Question under everyone a TextFormField (which is the userAnswer related to that exact question) what should I do in order to get the controller and value to work with after that.此代码会在每个人的 TextFormField 下生成 5 个问题对象(这是与该确切问题相关的 userAnswer)我应该做什么才能让controllervalue在此之后使用。

At this stage, when I enter a value in any TextFormField and press on the button , I get this error Unhandled Exception: type 'Null' is not a subtype of type 'List<TextEditingController>' of 'function result' which is pointing to this line在这个阶段,当我在任何 TextFormField 中输入一个值并按下按钮时,我收到此错误Unhandled Exception: type 'Null' is not a subtype of type 'List<TextEditingController>' of 'function result' which is pointing这条线

for (var i=0;i<GlobalParams.quizmodel.quizQuestions.length;i++){
              print({controllers[i].text});
            }

Any help is REALLY appreciated image任何帮助都非常感谢图片

class AnswerQuizPage extends StatefulWidget {
  const AnswerQuizPage({Key? key}) : super(key: key);

  @override
  State<AnswerQuizPage> createState() => _AnswerQuizPageState();
}

class _AnswerQuizPageState extends State<AnswerQuizPage> {
  int? _numPages ;
  int _currentPage = 1;
  bool test=false;
  var questionController= QuestionController(QuestionRepositoryImpl());
  //List<String> reponse=[];
  List<String> asnwers=[];
  List<TextEditingController>_reponse=[];
  List<TextEditingController> _controllers = [];
   late List<TextEditingController> controllers;
  late List<String> reponse;
  List<QuestionModel> listofquestion=[];
  List<QuizQuestion> listofquizquestionsforquiz=GlobalParams.quizmodel.quizQuestions;
  @override
  List<dynamic> trList=[];
  GlobalKey<FormState> globalFormKey=GlobalKey<FormState>();
  void show(){
    List<TextEditingController> _controllers2=[];
    String test;
    GlobalParams.quizmodel.quizQuestions.forEach((element) { final   quantityController =
    TextEditingController(text: element.userAnswer);
    controllers.add(quantityController);
    });
   /* for (var  i=0; i<listofquizquestionsforquiz.length;i++){
      TextEditingController text3ess;
      setState(() {
        //text3ess.text=listofquizquestionsforquiz[i].userAnswer;
       // _controllers2[i].text=test;
      });
    }*/
setState(() {
  _controllers2=controllers;
});

  }
  void initState(){
    super.initState();
    //controllers=[];
show();
  }
  @override
  Widget build(BuildContext context) {
    print(GlobalParams.quizmodel.id);
    Future<List<QuestionModel>> quizlist=questionController.getQuestionsByQuizId(GlobalParams.quizmodel.id);
    quizlist.then((value)  {
      //_numPages=value.length-2;
      listofquestion=value;
    });
    /*if (GlobalParams.model.name=="essai"){
      Future<List<QuestionModel>> quizlist=questionController.getQuestionsByQuizId(1);
      quizlist.then((value)  {
        //_numPages=value.length-2;
        listofquestion=value;
      });
    }
    if (GlobalParams.model.name=="spiderman concentration quiz"){
      Future<List<QuestionModel>> quizlist=questionController.getQuestionsByQuizId(2);
      quizlist.then((value)  {
        //_numPages=value.length-2;
        listofquestion=value;
      });
    }*/
   /* Future<List<QuestionModel>> quizlist=questionController.getQuestionsByQuizId(GlobalParams.quizmodel.id);
    quizlist.then((value)  {
      //_numPages=value.length-2;
      listofquestion=value;
    });*/
    _numPages=listofquestion.length;
    //print(listofquestion);
    int? idtochoose;
    return Scaffold(
      appBar:AppBar(
        elevation: 0,
        title:Text('répondre au quiz'),
        actions: <Widget>[
          //login
          Container(

            decoration: BoxDecoration(
              //color: Colors.orange[600],
                borderRadius: BorderRadius.circular(10)),
            margin: EdgeInsets.only(right: 15.0, top:5.0, bottom: 5.0,),
            child: Tooltip(
              message: "vous devez finir le quiz",
              child: Icon(Icons.more_horiz),
            ),
            /*IconButton(
              icon: const Icon(Icons.arrow_back),
              //padding: EdgeInsets.fromLTRB(0, auto, auto, bottom)
              tooltip: 'Show Snackbar',
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.pushNamed(context, "/superadminhomepage");
              },
            ),*/
          ),


        ],

      ),
      body: Container(
        margin: EdgeInsets.all(50),
        child: FutureBuilder<List<QuestionModel>>(
    future:questionController.getQuestionsByQuizId(GlobalParams.quizmodel.id),
    builder:(context ,snapshot){
    if(snapshot.connectionState==ConnectionState.waiting){
    return Center(child: CircularProgressIndicator(),);
    }
    if (snapshot.hasError){
    print('${snapshot.error}');
    print('${snapshot}');

    return Center(child: Text('${snapshot}'),);
    }
    return Column(
      children: [
        Expanded(child: buildBodyContent(snapshot, questionController)),
       /* QuizQuestionTextControllerWidget(controllers: _controllers, listofquizquestions: GlobalParams.quizmodel.quizQuestions, reponse: reponse),*/
        SizedBox(height: 50,),
        Container(
          child: FormHelper.submitButton("Ajouter", () async{


            print('hello');
            print('${GlobalParams.quizmodel.id}');
            print('${GlobalParams.quizmodel.quizQuestions[0].quizquestionpk.idQuestion}');
            /*for (var i=0;i<listofquizquestionsforquiz.length;i++){
              print("thabbet");
              print('réponse melowel ${ GlobalParams.quizmodel.quizQuestions[i].userAnswer}');
              print ("chouf");
            }*/
            /*for (var j=0;j<_controllers.length;j++){
              print('${_controllers[j].text}');
            }*/
            for (var j=0;j<reponse.length;j++){
              print('${reponse[j]}');
            }
         /*   for (TextEditingController c in _controllers) {c.dispose();}*/
            for (var i=0;i<GlobalParams.quizmodel.quizQuestions.length;i++){
              print({controllers[i].text});
            }
            print(controllers[0].text);
          },
            btnColor: Colors.blue,
            borderColor: Colors.white,
            txtColor: Colors.white,
            borderRadius: 10,),
        ),

      ],
    );

    },
    ),
      ),
    );
  }
}

SafeArea buildBodyContent (AsyncSnapshot <List<QuestionModel>> snapshot,
    QuestionController questionController){
 List <String> reponse=[];
  List<String> asnwers=[];
 List<QuizQuestion> listofquizquestions=GlobalParams.quizmodel.quizQuestions;
 List<TextEditingController> controllers=[];
 // List<TextEditingController> _reponse=[];
  List<TextEditingController> _controllers = [];
 int idx;

 GlobalParams.quizmodel.quizQuestions.forEach((element) { final   quantityController =
 TextEditingController(text: element.userAnswer);
 controllers.add(quantityController);
 });
  return SafeArea(
    child:
    Scrollbar(
      isAlwaysShown: true,
      thickness: 5,
     // scrollbarOrientation: ScrollbarOrientation.,
      child: ListView.builder(
          itemBuilder: (context,index)
          {
         //   _controllers.add(new TextEditingController());
            var cq=snapshot.data?[index];
            controllers.add( TextEditingController());
            listofquizquestions.map((e) { idx = listofquizquestions.indexOf(e);
            controllers.add( TextEditingController());
            } );

            return Column(
              children:[
                SizedBox(height: 10,),
                Container(
                  width: MediaQuery.of(context).size.width/2,
                  padding: EdgeInsets.only(top:5.0, bottom: 5.0, left: 10.0, right: 10.0),
                  decoration: BoxDecoration(
                    color: Colors.orange,
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height: 10,),
                      Text(cq!.enonce, style: TextStyle(
                        fontSize: 16,

                      ),
                      ),
                      SizedBox(height: 10,),
                      Text(
                        'réponse a : ${cq.propositionA}', style: TextStyle(
                        fontSize: 16,

                      ),),
                      SizedBox(height: 10,),
                      Text(
                        'réponse b : ${cq.propositionB}', style: TextStyle(
                        fontSize: 16,

                      ),),
                      SizedBox(height: 10,),
                      Text(
                        'réponse c : ${cq.propositionC}', style: TextStyle(
                        fontSize: 16,

                      ),),
                      SizedBox(height: 10,),
                      Text(
                        'réponse d : ${cq.propositionD}', style: TextStyle(
                        fontSize: 16,

                      ),),
                      SizedBox(height: 10,),

                    ],
                  ),
                ),
                SizedBox(height: 10,),
                /*TextFormField(
                  controller: _controllers[index],

                  onEditingComplete:(){ print(""); },
                  decoration: InputDecoration(
                    hintText: "nom du quiz",
                  ),
                  validator: (value){
                    setState(){

                    }
                    value="a";
                    if (value.isNotEmpty){
                     // _controllers.add(_controllers[index]);
                      print('${_controllers[index]}');
                      reponse[index]=value;
                      //asnwers.add(asnwers[index]);
                      // tr="QUATRE_A_CINQ";
                      return null;
                    } else {
                      return "libelle ne peut pas être vide";
                    }
                  },
                  keyboardType: TextInputType.text,
                ),*/
                /*Column(
                  // mainAxisSize : MainAxisSize.min,
                  children:[
                    ...(listofquizquestions).map((item) {
                      int idx = listofquizquestions.indexOf(item);
                      controllers.add(TextEditingController());
                      var j=0;
                      return  */
                        Column(
                          children: [
                            TextFormField(
                            controller: controllers[index],
                            //onEditingComplete: (text) {  print('First text field: $text');  },
                            decoration: InputDecoration(
                              hintText: ' réponse',
                            ),
                            validator: (value){
                              value="a";
                              if (value.isNotEmpty){
                                // _controllers.add(_controllers[index]);
                                print('${controllers[index].text}');
                                reponse.add(value);
                                //asnwers.add(asnwers[index]);
                                // tr="QUATRE_A_CINQ";
                                return null;
                              } else {
                                return "libelle ne peut pas être vide";
                              }
                            },
                            keyboardType: TextInputType.text,
                      ),
                          ],
                        ),
                   /* })
                  ],
                ),*/
                SizedBox(height: 10,),
              ],
            );
          },
          itemCount: snapshot.data?.length ??0),
    ),
  );
}

For solving this error: Unhandled Exception: type 'Null' is not a subtype of type 'List<TextEditingController>' of 'function result'解决此错误: Unhandled Exception: type 'Null' is not a subtype of type 'List<TextEditingController>' of 'function result'

Try writing this:试着写这个:

List<TextEditingController> controllers = [];

instead of:代替:

late List<TextEditingController> controllers;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM