flutter 我有一个ListView生成器,我想将TextEditingController的列表放置在列表中

bvjveswy  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(118)

我有一个ListView Builder,我想把一个TextEditingController的列表放在一个列表中。但是它给予了一个错误,“期望找到一个标识符”。我很困惑。

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ListViewBuilder extends StatefulWidget {
  const ListViewBuilder({super.key});

  @override
  State<ListViewBuilder> createState() => _ListViewBuilderState();
}

class _ListViewBuilderState extends State<ListViewBuilder> {
  final _formKey = GlobalKey<FormState>();
  // final TextEditingController controller;
  List validators = [
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the number';
      }
      return null;
    },
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the email';
      }
      return null;
    },
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the password';
      }
      return null;
    },
  ];
  List formatters = [
    FilteringTextInputFormatter.digitsOnly,
    FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
    FilteringTextInputFormatter.deny(RegExp(r'[/\\]'))
  ];
    ///Error happens here!!
  List controller = [
  final _name = TextEditingController();
  final _age = TextEditingController();
  final _height = TextEditingController();
  final _color = TextEditingController();
  final _dateofBirt = TextEditingController();
  final _Nationality = TextEditingController();

  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: ListView.builder(
          itemCount: 3,
          itemBuilder: (context, index) {
            return TextFormField(
              controller: controller[index],
              validator: validators[index],
              inputFormatters: [formatters[index]],
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('Click'),
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // If the form is valid, display a snackbar. In the real world,
            // you'd often call a server or save the information in a database.
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text('Processing Data')));
          }
        },
      ),
    );
  }
}

`
我将控制器设为变量,并尝试分别对其赋值,但仍出现错误。我将控制器设为变量,并尝试分别对其赋值,但仍出现错误。我将控制器设为变量,并尝试分别对其赋值,但仍出现错误。

b0zn9rqh

b0zn9rqh1#

如果你喜欢使用TextEditingController的列表,你不需要在单独的变量上分配它。

List controller = [
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
    TextEditingController(),
  ];

您也可以使用List.generate
现在,要获得您在第一项上定义的_name,您需要使用索引,如controller[0] for _name. _age for controller[1],,等等。
您可以获得如下文本
controller[index].text

相关问题