英文:
convert string to a specific class in flutter
问题
You can convert a string to the GenderData
class without manipulating the main array by creating a constructor or factory method in the GenderData
class that takes a string as a parameter. Here's how you can do it:
class GenderData {
final String name;
GenderData({required this.name});
factory GenderData.fromString(String name) {
return GenderData(name: name);
}
}
Then, in your code, you can use this factory method to convert a string to a GenderData
object:
currentName = GenderData.fromString(nameList[0]);
This way, you can keep your original array intact and still create GenderData
objects from the strings without modifying the array itself.
英文:
I have an array in a file and this is the content.
var nameList= ['Dirk', 'Luc', 'Bea', 'Frank', 'An', 'Lieve', 'Mia', 'Marc'];
.....................................................
There is a class in a file like this.
class GenderData { final String name; GenderData({required this.name});}
............................
if I try to use the first one in the array as an item in my statefulwidget i got the error that means I use a string instead of the GenderData class.
class Genderpage extends StatefulWidget {
@override
_GenderpageState createState() => _GenderpageState();
}
class _GenderpageState extends State<Genderpage> {
late GenderData currentName;
@override
void initState() {
super.initState();
currentName = nameList[0];
}
I would not like to change my array.
I used this command but it did not work too.
currentName = nameList[0] as GenderData;
Is there any way to convert a string to the class without manipulating the main array?
答案1
得分: 1
不能直接将字符串分配给不同类型的变量。只需创建一个GenderData对象并将其分配给变量,以便将变量设置为此类。
currentName = GenderData(name: nameList[0]);
另一个值得一提的是,如果你只会在类中存储一个性别的名字,我宁愿继续使用字符串。而如果你打算使用GenderData来存储更多属性,那就没问题。
英文:
You can not assign a string directly to a variable of a different type. You just need to create a GenderData object and assign it to the variable in case you want the variable as such.
currentName = GenderData(name: nameList[0]);
Another point worth mentioning is that if you will only store a gender's name in a class I would rather keep working with strings. Instead if you are going to use GenderData to store more properties then it is ok.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论