skip to Main Content

So I want to add a new textfield after i select an option but since I’m new to flutter I can’t figure it out on how to do it .

SelectFieldBloc selectFieldBloc = SelectFieldBloc(
                name: question.name,
                toJson: (option) => option?.optionText,
                validators: question.validation != null
                    ? [
                        (input) {
                          if (input != null) {
                            if (input is Option) {
                              Option option = input;
                              return inspectionValidator.inspect(
                                  option.optionText, question.validation);
                            } else if (input is SubOption) {
                              SubOption option = input;
                              return inspectionValidator.inspect(
                                  option.optionText, question.validation);
                            }
                          } else {
                            return inspectionValidator.inspect(
                                input, question.validation);
                          }
                        }
                      ]
                    : null,
                items: question.option);
            fieldBloc = selectFieldBloc;
            List<Widget> widgets = [];
            fieldBloc.onValueChanges(onData: (previous, current) async* {
              print(current.value?.optionText);
              if (current.value?.optionText == "Cultivated") {
                widgets.add(
                  TextFormField(
                    decoration: const InputDecoration(
                      border: UnderlineInputBorder(),
                      labelText: 'Enter your username',
                    ),
                  ),
                );
              }
            });
          }
          addFieldBloc(
            step: question.formId! - 1,
            fieldBloc: fieldBloc,
          );

I’ve tried to add a widget.add textfield but I don’t know where it went wrong.The following shows what I’ve done.

 fieldBloc = selectFieldBloc;
            List<Widget> widgets = [];
            fieldBloc.onValueChanges(onData: (previous, current) async* {
              print(current.value?.optionText);
              if (current.value?.optionText == "Cultivated") {
                widgets.add(
                  TextFormField(
                    decoration: const InputDecoration(
                      border: UnderlineInputBorder(),
                      labelText: 'Enter your username',
                    ),
                  ),
                );
              }

2

Answers


  1. Based on the code snippet you provided, it seems like you’re trying to dynamically add a TextFormField widget to a list called widgets when a specific option is selected in the selectFieldBloc. However, you haven’t specified what you want to do with the widgets list after adding the TextFormField.

    To display the TextFormField in your UI, you need to use a ListView or a similar widget that can render a list of widgets. Here’s an example of how you can modify your code to achieve this:

    import 'package:flutter/material.dart';
    
    // ...
    
    SelectFieldBloc selectFieldBloc = SelectFieldBloc(
      name: question.name,
      toJson: (option) => option?.optionText,
      validators: question.validation != null
          ? [
              (input) {
                if (input != null) {
                  if (input is Option) {
                    Option option = input;
                    return inspectionValidator.inspect(
                        option.optionText, question.validation);
                  } else if (input is SubOption) {
                    SubOption option = input;
                    return inspectionValidator.inspect(
                        option.optionText, question.validation);
                  }
                } else {
                  return inspectionValidator.inspect(
                      input, question.validation);
                }
              }
            ]
          : null,
      items: question.option,
    );
    
    fieldBloc = selectFieldBloc;
    List<Widget> widgets = [];
    
    // Assuming this code is within a stateful widget, you can define a state variable to track the selected option.
    Option? selectedOption;
    
    fieldBloc.onValueChanges(onData: (previous, current) async* {
      print(current.value?.optionText);
      if (current.value?.optionText == "Cultivated") {
        selectedOption = current.value;
      } else {
        selectedOption = null;
      }
      // Call setState to trigger a rebuild and update the UI.
      setState(() {});
    });
    
    // ...
    
    // In your build method, you can render the widgets list within a ListView.
    @override
    Widget build(BuildContext context) {
      return ListView(
        children: [
          // Render your other UI elements here.
          
          // Render the TextFormFields based on the selected option.
          if (selectedOption?.optionText == "Cultivated")
            ...widgets, // Use the spread operator to add the widgets from the list.
    
          // Render other UI elements.
        ],
      );
    }
    

    In this example, I assume you’re working within a stateful widget. When the selected option in the selectFieldBloc changes, the onValueChanges callback is triggered. If the selected option is "Cultivated," it sets the selectedOption variable to the current value. Then, setState is called to trigger a rebuild and update the UI.

    Within the build method, you can render the TextFormField widgets based on the selected option. If the selected option is "Cultivated," it uses the spread operator (…) to add the widgets from the widgets list to the UI.

    Make sure to adjust the code according to your specific requirements and the structure of your Flutter application.

    Login or Signup to reply.
  2. Look I don’t understand what exactly want to do, but If you want to add widget to list of widget you can simply create list and pass it into column or listview, when you add new widget re-render the UI using setState or one of the design patterns , also there is a widget call AnimtedList on flutter you can add or remove widget inside it ,
    AnimatedList
    https://api.flutter.dev/flutter/widgets/AnimatedList-class.html

    And there is an example for adding widget into list of widget

    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(MaterialApp(
          home: MyApp(),
        ));
    
    class MyApp extends StatefulWidget {
      const MyApp({super.key});
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<Widget> widgets = [];
      Widget _createFormField(
          {required TextEditingController controller, required String hint}) {
        return TextFormField(
          controller: controller,
          decoration: _inputDecoration(hint),
        );
      }
    
      int index = 0;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                widgets.add(
                  _createFormField(
                      controller: TextEditingController(),
                      hint: "field ${index++}"),
                );
                setState(() {});
              },
              child: Center(child: Text('Add field')),
            ),
            body: Visibility(
              visible: widgets.isNotEmpty,
              child: ListView.builder(
                  itemCount: widgets.length,
                  itemBuilder: (context, index) => widgets[index]),
              replacement: Center(child: Text('no items')),
            ));
      }
    
      InputBorder _border() => OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
            borderSide: BorderSide(
                width: 1,
                color: Colors.deepPurple.withOpacity(.2),
                style: BorderStyle.solid),
          );
      InputDecoration _inputDecoration(String hint) => InputDecoration(
            contentPadding: const EdgeInsets.symmetric(horizontal: 5),
            filled: true,
            enabledBorder: _border(),
            focusedBorder: _border(),
            border: _border(),
            disabledBorder: _border(),
            errorBorder: _border(),
            focusedErrorBorder: _border(),
            errorStyle: const TextStyle(color: Color(0xffff99c2)),
            fillColor: Colors.white,
            hintText: hint,
            alignLabelWithHint: true,
          );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search