flutter 为什么TextEditingController()不创建新控制器

jjhzyzn0  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(149)

有一个gridview是用TextFields的二维数组构建的,这样我就可以手动输入矩阵值了。函数本身看起来像这样:

//controller for row count input field
final rowsController = TextEditingController();
//controller for columns count input field
final columnsController = TextEditingController();
//2d array of TextFields
late List<List<TextField?>> matrix;
//2d array of Controllers for textfields above
late List<List<TextEditingController?>> controllers;

void createMatrix() {
   setState(() {
    //matrix variable becomes 2d array of nulls with reqired length
    matrix = List<List<TextField?>>.filled(int.tryParse(rowsController.text)!,
      List<TextField?>.filled(int.tryParse(columnsController.text)!, null), growable: true);

    //controllers variable becomes 2d array of nulls with reqired length (same len as matrix 2d list)
    controllers = List<List<TextEditingController?>>.filled(int.tryParse(rowsController.text)!,
        List<TextEditingController?>.filled(int.tryParse(columnsController.text)!, null), growable: true);
    
    //both lists are being filled with data
    for (int row = 0; row < int.tryParse(rowsController.text)!; row++) {
      for (int item = 0; item < int.tryParse(columnsController.text)!; item++) {
        //controller[x,y] becomes NEW TextEditingController()
        controllers[row][item] = TextEditingController();
        //each TextField is created and linked with its controller from controllers list
        matrix[row][item] = TextField(controller: controllers[row][item]);
      }
    }
  });
}

主要的问题是当我在创建的文本字段中输入一些内容时,它会将相同的值复制到列中的每一项中,如下所示:

看起来当TextField在for循环中创建时,它创建了一个引用而不是新对象,但TextEditingController()的构建器,但如果此方法的描述与此相反。
UPD.完整代码片段:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:number_inc_dec/number_inc_dec.dart';
import 'globals.dart';

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

  @override
  State<LabRab7> createState() => _LabRab7State();
}

class _LabRab7State extends State<LabRab7> {
  final rowsController = TextEditingController();
  final columnsController = TextEditingController();
  late List<List<TextField?>> matrix;
  late List<List<TextEditingController?>> controllers;
  @override
  void dispose() {
    rowsController.dispose();
    columnsController.dispose();
    for(var row in controllers){
      for(var item in row){
        item!.dispose();
      }
    }
    super.dispose();
  }
  @override
  void initState() {
    controllers = [
      [TextEditingController(), TextEditingController()],
      [TextEditingController(), TextEditingController()]
    ];
    matrix = [
      [
        TextField(controller: controllers[0][0]),
        TextField(controller: controllers[0][1])
      ],
      [
        TextField(controller: controllers[1][0]),
        TextField(controller: controllers[1][1])
      ]
    ];
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    void createMatrix() {
       setState(() {

        matrix = List<List<TextField?>>.filled(int.tryParse(rowsController.text)!,
      List<TextField?>.filled(int.tryParse(columnsController.text)!, null), growable: true);

        controllers = List<List<TextEditingController?>>.filled(int.tryParse(rowsController.text)!,
        List<TextEditingController?>.filled(int.tryParse(columnsController.text)!, null), growable: true);
    
        for (int row = 0; row < int.tryParse(rowsController.text)!; row++) {
          for (int item = 0; item < int.tryParse(columnsController.text)!; item++) {
            controllers[row][item] = TextEditingController();
            matrix[row][item] = TextField(controller: controllers[row][item]);
          }
        }
      });
    }

    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: () {
        for(var row in controllers){
          for(var item in row){
            if (kDebugMode) {
              print(item?.value.hashCode);
            }
          }
        }
        },),
        appBar: AppBar(
            leading: const BackButton(),
            backgroundColor: Notifiers.mainColor),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 150,
            child: Column(
              children: [
                const Text("Rows count:"),
                NumberInputWithIncrementDecrement(
                  controller: rowsController,
                  min: 2,
                  max: 6,
                  initialValue: 2,
                  onIncrement: (_) {
                    createMatrix();
                  },
                  onDecrement: (_) {
                    createMatrix();
                  },
                ),
                const SizedBox(height: 10),
                const Text("Columns count:"),
                NumberInputWithIncrementDecrement(
                  controller: columnsController,
                  max: 6,
                  min: 2,
                  initialValue: 2,
                  onIncrement: (_) {
                    createMatrix();
                  },
                  onDecrement: (_) {
                    createMatrix();
                  },
                )
              ],
            ),
          ),
          const SizedBox(height: 20),
          GridView.builder(
              shrinkWrap: true,
              itemCount: matrix.length * matrix[0].length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: matrix[0].length,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10),
              itemBuilder: (BuildContext ctx, index) {
                int gridStateLength = matrix[0].length;
                int x, y = 0;
                x = (index / gridStateLength).floor();
                y = (index % gridStateLength);
                return GestureDetector(
                  onTap: () {
                  },
                  child: GridTile(
                    child: Container(
                      decoration: BoxDecoration(
                          border:
                              Border.all(color: Colors.black, width: 0.5)),
                      child: Center(
                        child: matrix[x][y],
                      ),
                    ),
                  ),
                );
              }),
        ],
      ),
    ));
  }
}
mbzjlibv

mbzjlibv1#

你是对的,你的函数创建了新的对象,但是你创建文本域的Widget的函数可能实现错误,所以它不能正确地遍历行,所以对于函数中的每一行,它都将同一行传递给Widget。
由于缺少更多的代码,很难回答你的问题。

lymnna71

lymnna712#

日安!你能解决这个问题吗?如果你能分享任何解决方案,我将不胜感激,因为我面临类似的问题

相关问题