【问题标题】:Flutter how i can load list from other file?颤振我如何从其他文件加载列表?
【发布时间】:2020-10-01 12:14:31
【问题描述】:

我想将文件中的列表加载到小部件中,我有几个列表,应该加载一个带有 id 的特定列表。

这是我的代码:

main

 class Cars extends StatefulWidget {
  @override
  _carsState createState() => _carsState();
}

class _carsState extends State<cars> {
  List clist = [
     {'id': 'l0', 'name': 'BMW'},
     {'id': 'l1', 'name': 'Audi'},
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: clist.map((info) {
        return Container(
          margin: EdgeInsets.all(5),
          child: SizedBox(
            width: double.infinity,
            child: RaisedButton(
              padding: EdgeInsets.all(20),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(0.0),
              ),
              color: Colors.blue,
              child: Text(
                info['name'],
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Cars(name: info['name'], id: info['id'],)),
                );
              },
            ),
          ),
        );
      }).toList(),
    );
  }
}

cars.dart

 class Cars extends StatelessWidget {
  final String name;
  var id;

  Cars({Key key, this.name, this.id}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(name),
          backgroundColor: Colors.green,
          centerTitle: true,
        ),
        body: Column(
      children: LISTFROMOTHERFILE.map((info) {
        return Container(
          margin: EdgeInsets.all(5),
          child: SizedBox(
            width: double.infinity,
            child: Text(info['name'])
          ),
        );
      }).toList(),
    ));
  }
}

list.dart

      List l0 = [
  {'name': 'Example', 'PS': '500'},
  {'name': 'Example2', 'PS': '300'},
];

List l1 = [
  {'name': 'Example', 'PS': '300'},
];

现在,例如,如果 ID 1 是从 main 传输的,我希望加载列表 l0

我怎样才能意识到这一点,或者有更好的方法吗?

【问题讨论】:

  • 我会为此研究 JSON。这方面的大量文档

标签: list flutter


【解决方案1】:

最好让你的列表中的 POJO 类

class ExampleList{
   final String id;
   final String name ;
   final String PS;
   /// implement [fromJson] and [toJson] method if needed
}

现在,只要您需要它,只需传递整个对象而不是传递字符串。

你可以这样使用它

 Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Cars(ExampleList:ExampleList)),
                );

【讨论】:

  • 我想你不明白我想做什么
  • 哎呀!对不起。现在实现请参考这个stackoverflow.com/questions/49871170/…
  • 不,这也不同,我有不同的列表,想根据从主传输的 id 加载一个列表,这些列表又在 list.dart 中的一个额外文件中
猜你喜欢
  • 2019-06-22
  • 2020-07-17
  • 1970-01-01
  • 2020-12-08
  • 2014-06-21
  • 2020-04-24
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多