我将一个字符串从一个有状态的小部件传递到一个有态的小部件,我希望它被转换为int并存储在一个变量中



我正在将一个字符串从一个有状态的小部件传递到一个有态的小部件,我希望它被转换为int并存储在一个变量中,这样我就可以将它用作索引的值

class RecordNumber extends StatefulWidget {
final String recordName;
const RecordNumber(this.recordName, {super.key});
@override
RecordNumberState createState() => RecordNumberState();
}
class RecordNumberState extends State<RecordNumber> {
// I wanto initialize the variable recordName here as an integer
// final int index = (the rocordName);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Text(widget.recordName),
);
}
}

在状态类中创建一个变量

int recordNameIndex = 0;

在initState中,您可以将字符串解析为int。您必须在recordName之前编写小部件,因为您的变量在小部件类中,而不在状态中

@override
void initState() {
super.initState();
recordNameIndex = int.parse(widget.recordName);
}

您可以使用int.parse()将字符串解析为int

在你的代码中,它将是这样的:

final int index = int.parse(recordName);

例如:

int.parse("102") == 102  // true

相关内容

最新更新