![](/img/trans.png)
[英]Cannot pass variable value from one stateless Widget to another in Flutter
[英]Variable created in stateless widget cannot be used in child widgets (Flutter)
我對 Flutter 很陌生,我遇到了一個問題。 你或許能幫上忙!
錯誤信息是:
Undefined name 'myObjectList'.
Try correcting the name to one that is defined, or defining the name.
和代碼:
void main() => runApp(MyApp());
class myObject {
const myObject({this.objectName, this.added, this.price});
// final int id;
// final int userId;
final String objectName;
// final String category;
// final DateTime purchase;
final DateTime added;
final double price;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Mock data for objects (later to be retrieved from back-end)
const List<myObject> myObjectList = [
const myObject(objectName: 'TV', added: null, price: 12.25),
const myObject(objectName: 'Nintendo Switch', added: null, price: 122)
];
return MaterialApp(
title: "The Safe",
home: objectInventory(),
theme: ThemeData(primaryColor: Colors.blueGrey),
);
}
}
class objectInventory extends StatefulWidget {
_objectInventoryState createState() => _objectInventoryState();
}
class _objectInventoryState extends State<objectInventory> {
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text('The Safe')), body: myObjectList);
}
} // End of _objectInventoryState
我想將我的模擬數據定義到 MyApp class 中。 事實上,稍后,我想在應用啟動時從后端檢索數據。 有沒有辦法讓這些數據“全球化”?
謝謝
myObjectList
在方法體內部聲明,您應該在外部聲明它,在 class 內部
像這樣:
List<myObject> myObjectList = new List<myObject>();
更新
在 state 中,您可以使用小部件字段訪問StatlessWidget
實例。 所以它變成了這樣:
.... body: this.widget.myObjectList ....
如果我在所有函數/類之外定義列表,它會起作用。 這樣做,我可以從任何地方訪問它,並且可以在特定的 class 中填充列表。
就我而言,列表的初始加載將在 class 'MyApp' 中完成。
void main() => runApp(MyApp());
class myObject {
myObject({this.objectName, this.added, this.price});
// final int id;
// final int userId;
final String objectName;
// final String category;
// final DateTime purchase;
final DateTime added;
final double price;
}
List<myObject> myObjectList = new List<myObject>();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//List<myObject> myObjectList = new List<myObject>();
// Mock data for objects (later to be retrieved from back-end)
myObjectList.add(
myObject(objectName: 'TV', added: null, price: 12.25)
);
myObjectList.add(
myObject(objectName: 'Nintendo Switch', added: null, price: 122)
);
return MaterialApp(
title: "The Safe",
home: objectInventory(),
theme: ThemeData(primaryColor: Colors.blueGrey),
);
}
}
class objectInventory extends StatefulWidget {
objectInventoryState createState() => objectInventoryState();
}
class objectInventoryState extends State<objectInventory> {
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text('The Safe')), body: Text(myObjectList[1].objectName) );
}
}
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.