【问题标题】:How can I convert a Dart model class to a list without a builder?如何在没有构建器的情况下将 Dart 模型类转换为列表?
【发布时间】:2020-03-01 20:01:30
【问题描述】:

在 Flutter 应用程序中,我有一个 rxDart 块,它从 API 服务器获取 JSON 字符串并将其转换为类列表 (Sale)。

除了在 ListView 小部件上显示数据之外,我还想使用包 pdf: 1.3.23 打印数据。

pdf 包有一个构建器,但不会使用 ListView,因此我需要将我的销售列表转换为 List>,以便将其传递给 Table.fromTextArray。

或者,更一般地说,如何从解析的 API 响应创建 pdf?或者,我如何从数据创建 pdf?在显示数据之后,从颤动屏幕打印数据必须是第二个最常见的要求,但我在搜索中找不到关于如何去做的任何线索。

当我尝试将 SalesResponse 对象传递给 Table.fromTextArray 时收到此消息。

无法将参数类型“SalesResponse”分配给参数 键入列表>。

到目前为止,这是我的代码:

销售型号:

class Sale {
  int _id;
  int _billId;
  String _item;
  int _qty;
  double _price;

  Sale(sale) {
    _id = sale['id'];
    _billId = sale['bill_id'];
    _item = sale['item'];
    _qty = sale['qty'];
    _price = (sale['price'] as num).toDouble();
  }

  int get id => _id;
  int get billId => _billId;
  String get item => _item;
  int get qty => _qty;
  double get price => _price;
}

这是我的销售响应模型

import 'package:exactpos_mobile/model/sale.dart';

class SalesResponse {
  List<Sale> _sales = [];
  String error;

  SalesResponse.fromJson(Map<String, dynamic> parsedJson) {
    print(parsedJson);
    List<Sale> temp = [];
    if (parsedJson['sales'] != null) {
      for (int i = 0; i < parsedJson['sales'].length; i++) {
        Sale _sale = Sale(parsedJson['sales'][i]);
        temp.add(_sale);
      }
      _sales = temp;    
    }
  }

  SalesResponse.withError(String errorValue)
      : _sales = List(),
        error = errorValue;

  List<Sale> get sales => _sales;
}

销售存储库

class SaleRepository{
  ApiProvider _apiProvider = ApiProvider();

  Future<SalesResponse> getSales(int billId){
    return _apiProvider.getSales(billId);
  }
}

销售集团

import 'package:rxdart/rxdart.dart';

class SalesBloc {
  final SaleRepository _repository = SaleRepository();
  final PublishSubject<SalesResponse> _subject = PublishSubject<SalesResponse>();
  getSales(int billId) async {
    SalesResponse response = await _repository.getSales(billId); 
    _subject.sink.add(response);
  }
  void dispose() async{
    await _subject.drain();
    _subject.close();
  }
  PublishSubject<SalesResponse> get subject => _subject;
}
final salesBloc = SalesBloc();

这是我的小部件屏幕

SalesResponse salesList;

class SalesScreen extends StatefulWidget {

  static const routeName = '/sales';

  final Bill bill;
  final Tbl table;

  SalesScreen({    
    Key key,
    @required this.table,
    @required this.bill
   }) : super(key: key);

  @override
  State<StatefulWidget> createState() => SalesScreenState();      
}

class SalesScreenState extends State<SalesScreen> {

  @override
  void initState() {
    super.initState();

    salesBloc.getSales(widget.bill.id);

    salesList = salesBloc.getSales(widget.bill.id); 

      print('hello');
      print(salesList.sales);
      print('hello');
  }

  @override
  void dispose() {
    salesBloc.dispose();
    super.dispose();
  }
    @override
    Widget build(BuildContext context) {
    return Scaffold(
              drawer: AppDrawer(),
              appBar: AppBar(
                        backgroundColor: Colors.blue,

                        automaticallyImplyLeading: false,
                        centerTitle : true,
                        title: Text(widget.bill.billNumber.toString(), 
                                    style: TextStyle(color: Colors.white)
                                    ),
                        leading: IconButton(icon:Icon(Icons.arrow_back),
                                  onPressed:() =>
                        Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(
                             builder: (context) =>
                               BillsScreen(table: widget.table)), (Route<dynamic> route) => false)
                        )
              ),
              body: SafeArea(
                child: Container(
                       child: 
                          StreamBuilder<SalesResponse>(
                              stream: salesBloc.subject.stream,          
                              builder: (context, AsyncSnapshot<SalesResponse> snapshot) {
                                     if (snapshot.hasData) {
                                        if (snapshot.data.error != null && snapshot.data.error.length > 0) {
                                           return _buildErrorWidget(snapshot.data.error);
                                        }
                                        return _buildSalesListWidget(snapshot.data);
                                     } 
                              },
                          )
              ),
        ),

              floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
                 floatingActionButton: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[

                                 FloatingActionButton(
                                    heroTag: 1,
                                    backgroundColor: Colors.yellow,
                                    onPressed: () {
                                        Printing.layoutPdf(onLayout:(format)=> 
                                           buildReceipt(widget.table, 
                                                        widget.bill, 
                                                        salesList));
                                    },
                                    child: Icon(FontAwesomeIcons.print),
                                 ),
                              ],
                    ),
                )

    );

  }

  Widget _buildSalesListWidget(SalesResponse data) {

          return ListView.builder(            
                     itemCount: data.sales.length,
                     itemBuilder: (context, index) {

                         return ListTile(                                             
                                  title: Text(                                            
                                              data.sales[index].item,                                          
                                              style: TextStyle(
                                                         fontWeight: FontWeight.w500,        
                                                         fontSize: 20,
                                              ),
                                  ),
                                  subtitle: Text('qty' + ' ' + data.sales[index].qty.toString() + ', ' + 'price' + ' ' + data.sales[index].price.toStringAsFixed(2)),
                                  leading: Icon(
                                                FontAwesomeIcons.beer,
                                                color: Colors.blue[500],
                                  ),           
                                  onTap: () {},
                         );
                     },
        );
  }
 }

最后,我的 pdf 代码

Future<List<int>> buildReceipt(Tbl table, Bill bill,  SalesResponse salesList)  async {

  const PdfPageFormat format = PdfPageFormat(160, 900);

  final Document pdf = Document();

    pdf.addPage(MultiPage(

      pageFormat: format, //  PdfPageFormat.a4.copyWith(marginBottom: 1.5 * PdfPageFormat.cm),

      crossAxisAlignment: CrossAxisAlignment.start,

      header: (Context context) {

        if (context.pageNumber == 1) {
          return null;
        }

        return Container(

            alignment: Alignment.centerRight,

            margin: const EdgeInsets.only(top: 3.0 * PdfPageFormat.mm),

            padding: const EdgeInsets.only(bottom: 3.0 * PdfPageFormat.mm),

            decoration: const BoxDecoration(
                border:
                    BoxBorder(bottom: true, width: 0.5, color: PdfColors.grey)),

            child: Text('Exact POS',
                style: Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },
      footer: (Context context) {
        return Container(
            alignment: Alignment.centerRight,
            margin: const EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
            child: Text('Page ${context.pageNumber} of ${context.pagesCount}',
                style: Theme.of(context)
                    .defaultTextStyle
                    .copyWith(color: PdfColors.grey)));
      },
      build: (Context context) => <Widget>[
            Header(
                level: 0,
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text('Exact POS', textScaleFactor: 2),
                      PdfLogo()
                    ]
                )
            ),

            Padding(padding: const EdgeInsets.all(4)),

            Paragraph(text: table.number),

            Table.fromTextArray(context: context, data: salesList  ),
      ]
    )
  );
  return pdf.save();
}

【问题讨论】:

  • 目前还没有办法在 Dart 中自动执行此类操作。您要么必须自己列出所有属性,要么制作一些代码生成器。可以使用反射,但 dart:mirrors 库不适用于颤振框架。
  • 我将如何“列出属性”?
  • 类似这样的东西:List&lt;String&gt; get stringProps =&gt; [_id, _billId, _item, _qty, _price].map((p) =&gt; p.toString()).toList();

标签: flutter dart


【解决方案1】:

问题是 Table.fromTextArray 期望 List&lt;List&lt;String&gt;&gt; 作为 data 而你传递的是 SalesResponse

这里有一个简单的例子来说明如何做到这一点:

Table.fromTextArray(context: context, data: <List<String>>[
  <String>['Id', 'Bill Id', 'Item', 'Qty', 'Price'],
  ...salesList.sales.map((s) =>
  ['${s.id}', '${s.billId}', '${s.item}', '${s.qty}', '${s.price}']),
])

或者在Sale中创建一个getter来获取列表,像这样:

List<String> get stringList => ['$id', '$billId', '$item', '$qty', '$price'];

然后像这样使用它:

Table.fromTextArray(context: context, data: <List<String>>[
  <String>['Id', 'Bill Id', 'Item', 'Qty', 'Price'],
  ...salesList.sales.map((sale) => sale.stringList),
])

或者直接在SalesResponse中创建一个getter来获取list的列表,像这样:

List<List<String>> get salesStringList =>
    <List<String>>[
      <String>['Id', 'Bill Id', 'Item', 'Qty', 'Price'],
      ...sales.map((sale) => sale.stringList),
    ];

然后像这样使用它:

Table.fromTextArray(context: context, data: salesList.salesStringList)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2014-04-05
    • 2017-04-05
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2017-09-20
    相关资源
    最近更新 更多