我有两个文本字段都具有相同的窗口小部件类型,并且我想访问这两个字段的数据。但要跟踪它是什么类型的数据(即:是否为人名)或城市名称)。
这就是我的管理方式:
1。在TextInputField中创建一个id变量(它是一个无状态窗口小部件)。 2.在调用onChange函数时比较了该ID变量。 3.根据其名称分配值。
请告诉我是否有人知道执行此操作的适当方法,因为这似乎有点怪异。如果您有更好的选择,请Plz提供代码。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
print("City is :${Data.city} Name is :${Data.name}"); //getting the values print
},
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextInputFiled(
iconData: Icons.account_circle,
hintText: "Name",
fieldId: "name",
),
SizedBox(
height: 20,
),
TextInputFiled(
iconData: Icons.adjust,
hintText: "City Name",
fieldId: "city",
),
],
),
),
),
),
);
}
}
//Creating a stateless widget named TextInputFiled
class TextInputFiled extends StatelessWidget {
final String hintText;
final IconData iconData;
final String fieldId; //field id for verifying different input
TextInputFiled({this.iconData, this.hintText, this.fieldId});
@override
Widget build(BuildContext context) {
return TextField(
onChanged: (value) {
if (fieldId == "city") //checking for type of value using field id
Data.city = value;
else
Data.name = value;
},
decoration: InputDecoration(
hintText: this.hintText,
fillColor: Colors.white70,
filled: true,
prefixIcon: Icon(iconData),
),
);
}
}
class Data { //Data class for transfering data
static String name;
static String city;
}