Как ограничить динамическое текстовое поле до 4 в flutter?

#flutter #dart

#flutter #dart

Вопрос:

Это код для модуля Createpoll моего приложения для опроса. Я хочу сгенерировать всего 4 динамических текстовых поля, но приведенный ниже код генерирует неограниченное количество текстовых полей. Я не могу понять, какую часть редактировать в соответствии с моими потребностями.

Создать скриншот опроса

Я также не могу внести изменения в текст подсказки в текстовом поле, он продолжает повторять «Вариант 1», я хочу, чтобы он выглядел как вариант 1, Option2…..so вкл.

 import 'package:flutter/material.dart';
import 'package:justpoll/Constants.dart';
import 'package:justpoll/screens/create_poll/create_poll2.dart';
import 'package:justpoll/widgets/custom_input.dart';

class CreatePoll extends StatefulWidget {
  @override
  _CreatePollState createState() => _CreatePollState();
}

class _CreatePollState extends State<CreatePoll> {
  final _formKey = GlobalKey<FormState>();
  TextEditingController _nameController;
  static List<String> friendsList = [null];

  String emoji_id;
  List<String> emoji = [
    "❤️",
    "🤩",
    "✌️",
    "😂",
    "😡",
  ];

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: MyColors.white,
        appBar: AppBar(
          title: Padding(
            padding: const EdgeInsets.all(75.0),
            child: Text('New Poll'),
          ),
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(
              Icons.close,
            ),
          ),
          backgroundColor: Colors.black87,
        ),
        body: ListView(
          children: [
            Form(
              key: _formKey,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // name textfield

                    Center(
                      child: Padding(
                        padding: const EdgeInsets.all(6.0),
                        child: Text("1/4"),
                      ),
                    ),

                    Padding(
                      padding: const EdgeInsets.only(right: 32.0),
                      child: CustomInput(
                        textEditingController: _nameController,
                        labletext: 'Question?*',
                        decoration: InputDecoration(hintText: 'Question*'),
                        validator: (v) {
                          if (v.trim().isEmpty) return 'Please enter something';
                          return null;
                        },
                      ),
                    ),

                    SizedBox(
                      height: 20,
                    ),

                    // Text(

                    //   'Options',

                    //   style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16),

                    // ),

                    // Padding(
                    //   padding: const EdgeInsets.only(right: 2.0),
                    //   child: Row(
                    //     children: [
                    //       Expanded(
                    //         flex: 2,
                    //         child: Padding(
                    //           padding: const EdgeInsets.only(right: 20),
                    //           child: CustomInput(
                    //             textEditingController: _nameController,
                    //             labletext: 'Option 1*',
                    //             decoration: InputDecoration(hintText: 'Option'),
                    //             validator: (v) {
                    //               if (v.trim().isEmpty)
                    //                 return 'Please enter something';

                    //               return null;
                    //             },
                    //           ),
                    //         ),
                    //       ),
                    //       Expanded(
                    //         flex: 1,
                    //         child: Padding(
                    //           padding: const EdgeInsets.only(right: 30),
                    //           child: Container(
                    //             padding: EdgeInsets.only(left: 10, right: 16),
                    //             decoration: BoxDecoration(
                    //                 border: Border.all(
                    //                     color: MyColors.black, width: 1.5),
                    //                 borderRadius: BorderRadius.circular(10)),
                    //             child: DropdownButton(
                    //               hint: Text('❤️'),
                    //               value: emoji_id,
                    //               icon: Icon(Icons.arrow_drop_down),
                    //               iconSize: 36,
                    //               isExpanded: true,
                    //               underline: SizedBox(),
                    //               style: TextType.regularDarkText,
                    //               onChanged: (newValue) {
                    //                 setState(() {
                    //                   emoji_id = newValue;
                    //                 });
                    //               },
                    //               items: emoji.map((emoji_id) {
                    //                 return DropdownMenuItem(
                    //                   value: emoji_id,
                    //                   child: Text(emoji_id),
                    //                 );
                    //               }).toList(),
                    //             ),
                    //           ),
                    //         ),
                    //       ),
                    //     ],
                    //   ),
                    // ),

                    ..._getOptions(),

                    SizedBox(
                      height: 30,
                    ),

                    Align(
                      alignment: Alignment.bottomRight,
                      child: MaterialButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => CreatePoll2(),
                            ),
                          );
                        },
                        color: Colors.black,
                        textColor: Colors.white,
                        child: Icon(
                          Icons.arrow_forward,
                          size: 24,
                        ),
                        padding: EdgeInsets.all(16),
                        shape: CircleBorder(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// get friends text-fields
  List<Widget> _getOptions() {
    List<Widget> friendsTextFields = [];
    for (int i = 0; i < friendsList.length; i  ) {
      friendsTextFields.add(Padding(
        padding: const EdgeInsets.symmetric(vertical: 16.0),
        child: Row(
          children: [
            Expanded(child: FriendTextFields(i)),
            SizedBox(
              width: 5,
            ),
            // we need add button at last friends row
            _addRemoveButton(i == friendsList.length - 1, i),
          ],
        ),
      ));
    }
    return friendsTextFields;
  }

  /// add / remove button
  Widget _addRemoveButton(bool add, int index) {
    return InkWell(
      onTap: () {
        if (add) {
          // add new text-fields at the top of all friends textfields
          friendsList.insert(0, null);
        } else
          friendsList.removeAt(index);
        setState(() {});
      },
      child: Container(
        width: 26,
        height: 26,
        decoration: BoxDecoration(
          color: (add) ? Colors.black : Colors.red,
          borderRadius: BorderRadius.circular(20),
        ),
        child: Icon(
          (add) ? Icons.add : Icons.remove,
          color: Colors.white,
        ),
      ),
    );
  }
}

class FriendTextFields extends StatefulWidget {
  final int index;
  FriendTextFields(this.index);
  @override
  _FriendTextFieldsState createState() => _FriendTextFieldsState();
}

class _FriendTextFieldsState extends State<FriendTextFields> {
  TextEditingController _nameController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  String emoji_id;
  List<String> emoji = [
    "❤️",
    "🤩",
    "✌️",
    "😂",
    "😡",
  ];
  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _nameController.text = _CreatePollState.friendsList[widget.index] ?? '';
    });

    return Row(
      children: [
        Expanded(
          flex: 2,
          child: CustomInput(
            textEditingController: _nameController,
            labletext: 'Option 1*',
            decoration: InputDecoration(hintText: 'Option'),
            validator: (v) {
              if (v.trim().isEmpty) return 'Please enter something';

              return null;
            },
          ),
        ),
        Expanded(
          flex: 1,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              padding: EdgeInsets.only(left: 10, right: 16),
              decoration: BoxDecoration(
                  border: Border.all(color: MyColors.black, width: 1.5),
                  borderRadius: BorderRadius.circular(10)),
              child: DropdownButton(
                hint: Text('❤️'),
                value: emoji_id,
                icon: Icon(Icons.arrow_drop_down),
                iconSize: 36,
                isExpanded: true,
                underline: SizedBox(),
                style: TextType.regularDarkText,
                onChanged: (newValue) {
                  setState(() {
                    emoji_id = newValue;
                  });
                },
                items: emoji.map((emoji_id) {
                  return DropdownMenuItem(
                    value: emoji_id,
                    child: Text(emoji_id),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
 

Ответ №1:

Во-первых, если вы хотите ограничить его только 4 динамическими полями, пожалуйста, замените эту строку

_addRemoveButton(i == friendsList.length - 1, i)

с помощью этого

_addRemoveButton(i < 3 ? i == friendsList.length - 1 : false, i),

Это позволит убедиться, что кнопка добавить не отображается в 4-м поле. Вместо этого он покажет кнопку удаления для 4-го поля.

Во-вторых, чтобы оно отображало каждое поле как вариант 1, вариант 2, вариант 3 и т. Д., Замените строку

labletext: 'Option 1*',

с

labletext: 'Option ${widget.index 1}',