将字符串转换为Flutter中的特定类。

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月15日 07:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定