我正在嘗試在顫振中創建一個測驗應用程式,我的想法是我有一個 JSON 檔案來描述要問的問題,我應該閱讀 JSON 檔案并在我的應用程式中列印出問題,我可以閱讀 JSON 檔案很好,但是當我嘗試將其列印到應用程式時,我得到了上面的錯誤
我像這樣閱讀Json檔案:`
var items = [];
/********** Function to read Json file **************************/
@override
void initState() {
super.initState();
readJson();
}
Future<void> readJson() async
{
final String response = await rootBundle.loadString('assets/questions.json');
final data = await json.decode(response);
setState(() {
items = data["Questions"];
});
print(items);
print(items[0]);
/*****************************************************************/
}
The file is read correctly, since the data is printed correctly in the console, however, when I try to use it in a Text Widget like so:
Widget question = Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
margin:
const EdgeInsets.only(left: 20.0, right: 20.0, top: 40, bottom: 30),
alignment: Alignment.centerLeft,
child: const Text(
"Question 1:",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
),
),
Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(bottom: 80),
child: Text(
items[0]["description"]
/* style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 30, color: Colors.white),*/
),
)
],
);
我收到上面的錯誤,有什么想法嗎?謝謝你`
uj5u.com熱心網友回復:
您無法訪問構建方法之外的變數。如果您正在創建一個輔助方法,請用這樣的函式將其括起來,以便您能夠訪問變數。
Widget question() => Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
margin:
const EdgeInsets.only(left: 20.0, right: 20.0, top: 40, bottom: 30),
alignment: Alignment.centerLeft,
child: const Text(
"Question 1:",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
),
),
Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(bottom: 80),
child: Text(
items[0]["description"]
/* style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 30, color: Colors.white),*/
),
)
],
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526469.html
標籤:扑镖小部件
