在无状态小部件中创建的变量不能在子小部件中使用(Flutter)

时间:2020-04-18 23:26:31

标签: 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类中。确实,稍后,我想在应用启动时从后端检索数据。 有没有办法使这些数据“全局”?

谢谢

2 个答案:

答案 0 :(得分:0)

myObjectList是在方法主体内部声明的,应该在类内部外部声明

赞:

List<myObject> myObjectList = new List<myObject>();

更新

在状态内,您可以使用小部件字段访问StatlessWidget实例。这样就变成了这样:

.... body: this.widget.myObjectList   ....

答案 1 :(得分:0)

如果我在所有函数/类之外定义了列表,则可以使用。这样做,我可以从任何地方访问它,并可以在特定类中填充列表。

就我而言,列表的初始加载将在“ 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) );
  }
}

谢谢