如何将数据传递到PDF页面构建功能

时间:2019-11-03 01:47:11

标签: flutter

我正在构建我的第一个Flutter应用程序。

我从屏幕上的浮动操作按钮调用了此函数,但无法弄清楚如何将数据对象传递给此函数。

有人可以帮忙吗?该函数将不接受任何参数。

我这样调用函数:

我这样称呼它:

                         FloatingActionButton(
                                heroTag: 1,
                                backgroundColor: Colors.yellow,
                                onPressed: () {
                                  Printing.layoutPdf(onLayout: buildReceipt);
                                  },
                                child: Icon(FontAwesomeIcons.print),
                             ),

这是我的代码:

import 'dart:async';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';

Future<List<int>> buildReceipt(PdfPageFormat format)  async {

final Document pdf = Document();

pdf.addPage(MultiPage(

  pageFormat: 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(bottom: 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('Portable Document Format',
            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('Portable Document Format', textScaleFactor: 2),
                  PdfLogo()
                ])),
        Padding(padding: const EdgeInsets.all(10)),
        Paragraph(
            text:
                'I want to display this ${data}')
      ]));

  return pdf.save();
}

1 个答案:

答案 0 :(得分:2)

嗨,您可以将代码更改为此

FloatingActionButton(
                                heroTag: 1,
                                backgroundColor: Colors.yellow,
                                onPressed: () {
                                  Printing.layoutPdf(onLayout:(format)=> buildReceipt(format, data1, data2, data3));
                                  },
                                child: Icon(FontAwesomeIcons.print),
                             ),

然后还更改您的函数以匹配方法调用

Future<List<int>> buildReceipt(PdfPageFormat format, data1, data2, data3)  async {
//bla bla bla
}