Flutter - Create dynamic number of texteditingcontrollers

前端 未结 3 1262
我在风中等你
我在风中等你 2020-12-16 23:55

I am recreating an app I have previously made in Swift, and on one of my pages we call an API and based on the results, we present the user a dynamic number of textfields to

相关标签:
3条回答
  • 2020-12-17 00:14

    I just modified @Felix's answer with using Map to store TextEditingControllers instead of list. I think its easy to call textEditingControllers with key value pairs. Modified code block;

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: "MyHomePage",
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(
            title: "MyHomePage",
          ),
        );
      }
    }
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      @override
      Widget build(BuildContext context) {
        var stringListReturnedFromApiCall = ["first", "second", "third", "fourth", "..."];
        // This list of controllers can be used to set and get the text from/to the TextFields
        Map<String,TextEditingController> textEditingControllers = {};
        var textFields = <TextField>[];
        stringListReturnedFromApiCall.forEach((str) {
          var textEditingController = new TextEditingController(text: str);
          textEditingControllers.putIfAbsent(str, ()=>textEditingController);
          return textFields.add( TextField(controller: textEditingController));
        });
    
        return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: SingleChildScrollView(
                child: new Column(
                  children:[
                  Column(children:  textFields),
                    RaisedButton(
                      child: Text("Print Values"),
                        onPressed: (){
                        stringListReturnedFromApiCall.forEach((str){
                          print(textEditingControllers[str].text);
                        });
                      })
                  ]
                )));
      }
    }
    

    when you write something to textfields and hit to print button results ;

    flutter: first controller text
    flutter: second controller text
    flutter: third controller text
    flutter: fourth controller text
    flutter: so on .......
    
    0 讨论(0)
  • 2020-12-17 00:21

    More or less as @Günter Zöchbauer mentioned, you can just build a list of widgets which are nested then in a container.

    Here's a simple example:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: "MyHomePage",
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(
            title: "MyHomePage",
          ),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        var stringListReturnedFromApiCall = ["first", "second", "third", "fourth", "..."];
    
        // This list of controllers can be used to set and get the text from/to the TextFields
        var textEditingControllers = <TextEditingController>[];
    
        var textFields = <TextField>[];
        stringListReturnedFromApiCall.forEach((str) {
          var textEditingController = new TextEditingController(text: str);
          textEditingControllers.add(textEditingController);
          return textFields.add(new TextField(controller: textEditingController));
        });
    
        return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: SingleChildScrollView(
                child: new Column(
              children: textFields,
            )));
      }
    }
    

    Edit: Added list for TextEditingControllers to interact with all the TextFields

    0 讨论(0)
  • 2020-12-17 00:21

    May be this can help you or other's as well.

    createFieldsList(context) {
        thirdStepUserRegistration.value.forEach((key, value) { //// This line will loop all your data [ValueNotifier<Map<String, dynamic>> thirdStepUserRegistration]
          if (!fieldsController.containsKey(key)) {
            fieldsController[key] = TextEditingController(); //// This one will create you a list of controllers that u need for your fiels [Map<String, TextEditingController> fieldsController]
            fieldsList.add( ////You will be creating a list of widget which is textfields [List<Widget> fieldsList]
              Container(
                height: 40.0,
                margin: EdgeInsets.only(bottom: 10),
                width: MediaQuery.of(context).size.width - 100,
                child: PrimaryTextFormField( //This is my customize textfield you can create yours
                  controller: fieldsController[key],
                  keyboardType: TextInputType.text,
                  textCapitalization: TextCapitalization.words,
                  inputFormatters: textFormatter(),
                  hintText: value,
                ),
              )
            );
          }
        });
      }
    
      Column additionalDetails(BuildContext context) {
        createFieldsList(context);
        return Column( children: fieldsList );
      }
    
    0 讨论(0)
提交回复
热议问题