我來自打字稿背景和飛鏢新手,在打字稿中,我們能夠定義介面并將這些型別附加到具有正確格式的所需變數上,例如
interface Answer {
text: string;
value: number;
}
interface Question {
question: string;
answers: Answer[
}
const questions: Question[] = [
{
'question': "What's your fav color?",
'answers': [
{
'text': 'one',
'value': 1,
},
{
'text': 'one',
'value': 2,
},
{
'text': 'one',
'value': 3,
},
{
'text': 'one',
'value': 4,
},
],
},
];
這僅適用于打字稿,我不會收到任何錯誤。
但在飛鏢中,我無法實作同樣的目標。下面是我的飛鏢代碼。請幫助我,我收到一條錯誤訊息The element type 'Map<String, Object>' can't be assigned to the list type 'SingleQuestion'.
是否有任何資源可以幫助我克服打字稿到飛鏢遷移的問題,這將是最好的建議。
https://dartpad.dev/?id=bcef24b3cbd94a2150454cf0edea3704
uj5u.com熱心網友回復:
實際上你的資料是json。然后對您的資料使用 Object 類,對 SingleQuestion 使用 fromJson 函式。你的主要功能是這樣的:
void main() {
Object data = {
'question': "What's your fav color?",
'answers': [
{
'text': 'red',
'value': 1,
},
{
'text': 'green',
'value': 2,
},
{
'text': 'yellow',
'value': 3,
},
{
'text': 'black',
'value': 4,
},
],
};
final List<SingleQuestion> questions = [SingleQuestion.fromJson(data)];
print(questions[0].question);
print(questions[0].answers[1].value);
print(questions[0].answers[1].text);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/476340.html
下一篇:將基于函式的草圖面向物件
