我正在重新创建一个以前在Swift中制作的应用程序,在我的其中一个页面上我们调用了API,并根据结果向用户显示了动态数量的文本字段,可通过不同的搜索参数进行搜索。
在Dart/Flutter中有什么好方法吗?由于dart不支持在运行时生成代码,这甚至有可能吗?
最佳答案
我刚刚修改了@Felix的答案,使用 map 来存储TextEditingControllers而不是列表。我认为使用键值对调用textEditingControllers很容易。
修改后的代码块;
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);
});
})
]
)));
}
}
当您在文本字段中写东西并点击打印按钮结果时;
flutter: first controller text
flutter: second controller text
flutter: third controller text
flutter: fourth controller text
flutter: so on .......
关于dynamic - Flutter-创建动态数量的texteditingcontrollers,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50766139/