在Flutter中将列表视图构建器导出到CSV文件

2exbekwf  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(124)

我试图在Flutter中将列表视图导出为CSV文件。
x1c 0d1x的数据
该表是基于Listview. separator创建的。
下面是pubsec.yaml



下面是完整的代码:

import 'package:flutter/material.dart';
//import 'package:custom_searchable_dropdown/custom_searchable_dropdown.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:csv/csv.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_html/flutter_html.dart';

//import 'package:table_calendar/table_calendar.dart';

//CUSTOMER LOGIN PAGE

class CustomerHomePage extends StatelessWidget {
  const CustomerHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text("Customer Home Page"),
        titleSpacing: 00.0,
        centerTitle: true,
        toolbarHeight: 60.2,
        toolbarOpacity: 0.8,
        /*shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                bottomRight: Radius.circular(25),
                bottomLeft: Radius.circular(25)),
          ),*/
        elevation: 0.00,
        backgroundColor: Colors.black,
      ),
      body: Container(
          decoration: BoxDecoration(
            color: Colors.blue,
          ),
          child: SingleChildScrollView(
            child: C_HP(),
          )),
    );
  }
}

class CustomClipPath extends CustomClipper<Path> {
  var radius = 5.0;
  @override
  Path getClip(Size size) {
    Path path_0 = Path();
    path_0.moveTo(size.width * -0.0011400, size.height * 0.9983000);
    path_0.quadraticBezierTo(size.width * -0.0003900, size.height * 0.4740200,
        size.width * -0.0001400, size.height * 0.1430800);
    path_0.quadraticBezierTo(size.width * 0.0711000, size.height * 0.1000800,
        size.width * 0.0991200, size.height * 0.0999800);
    path_0.cubicTo(
        size.width * 0.3005300,
        size.height * 0.0946400,
        size.width * 0.7033400,
        size.height * 0.0942600,
        size.width * 0.9047500,
        size.height * 0.0952200);
    path_0.quadraticBezierTo(size.width * 0.9412100, size.height * 0.1006200,
        size.width * 0.9992900, size.height * 0.1488200);
    path_0.lineTo(size.width * 1.0015400, size.height * 1.0009800);
    path_0.quadraticBezierTo(size.width * 0.7492650, size.height * 0.9938900,
        size.width * -0.0011400, size.height * 0.9983000);
    return path_0;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

// stateful widget created for calendar class
class C_HP extends StatefulWidget {
  @override
  _CHPState createState() => _CHPState();
}

class _CHPState extends State<C_HP> {
  List<String> items = [
    "Maid 1",
    "Maid 2",
    "Maid 3",
    "Maid 4",
    "Maid 5",
    "Maid 6",
    "Maid 7",
    "Maid 8",
    "Maid 9",
    "Maid 10"
  ];
  String dropdownSelected = '';
  List<String> selectedValue1 = [];
  String jsonstring_names = "";
  int index1 = 0;
  int updated = 0;
  // bool _value = false;
  bool _valu1 = false;
  bool _valu2 = false;
  bool _valu3 = false;

  @override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      SizedBox(
        height: 10,
      ),
      Row(children: <Widget>[
        SizedBox(
          width: 10,
        ),
        Flexible(
          child: SizedBox(
              height: 80,
              width: 500,
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                      offset: const Offset(
                        3.0,
                        3.0,
                      ), //Offset
                      blurRadius: 10.0,
                      spreadRadius: 2.0,
                    ), //BoxShadow
                    BoxShadow(
                      color: Colors.white,
                      offset: const Offset(0.0, 0.0),
                      blurRadius: 0.0,
                      spreadRadius: 0.0,
                    ), //BoxShadow
                  ],
                ),
                child: CheckboxListTile(
                  title: const Text('Cleaning'),
                  subtitle: const Text(
                      'select the checkbox to have Cleaning services'),
                  secondary: Container(
                    height: 50,
                    width: 50,
                    child: Image.asset(
                      "assets/images/cleaning.jpg",
                      fit: BoxFit.cover,
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.0), // Optionally
                    side: const BorderSide(color: Colors.green),
                  ),
                  autofocus: false,
                  isThreeLine: true,
                  activeColor: Colors.blue,
                  checkColor: Colors.white,
                  selected: _valu1,
                  value: _valu1,
                  onChanged: (bool? value1) {
                    setState(() {
                      _valu1 = value1 ?? true;
                    });
                  },
                ),
              )),
        ),
        SizedBox(
          width: 10,
        ),
        Flexible(
          child: SizedBox(
              height: 80,
              width: 500,
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                      offset: const Offset(
                        3.0,
                        3.0,
                      ), //Offset
                      blurRadius: 10.0,
                      spreadRadius: 2.0,
                    ), //BoxShadow
                    BoxShadow(
                      color: Colors.white,
                      offset: const Offset(0.0, 0.0),
                      blurRadius: 0.0,
                      spreadRadius: 0.0,
                    ), //BoxShadow
                  ],
                ),
                child: CheckboxListTile(
                  title: const Text('Cooking'),
                  subtitle: const Text(
                      'select the checkbox to have cooking services'),
                  secondary: Container(
                    height: 50,
                    width: 50,
                    child: Image.asset(
                      "assets/images/cooking.jpg",
                      fit: BoxFit.cover,
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.0), // Optionally
                    side: const BorderSide(color: Colors.green),
                  ),
                  autofocus: false,
                  isThreeLine: true,
                  activeColor: Colors.blue,
                  checkColor: Colors.white,
                  selected: _valu2,
                  value: _valu2,
                  onChanged: (bool? value2) {
                    setState(() {
                      _valu2 = value2 ?? true;
                    });
                  },
                ),
              )),
        ),
        SizedBox(
          width: 10,
        ),
        Flexible(
          child: SizedBox(
              height: 80,
              width: 500,
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                      offset: const Offset(
                        3.0,
                        3.0,
                      ), //Offset
                      blurRadius: 10.0,
                      spreadRadius: 2.0,
                    ), //BoxShadow
                    BoxShadow(
                      color: Colors.white,
                      offset: const Offset(0.0, 0.0),
                      blurRadius: 0.0,
                      spreadRadius: 0.0,
                    ), //BoxShadow
                  ],
                ),
                child: CheckboxListTile(
                  title: const Text('Elderly Care'),
                  subtitle: const Text(
                      'select the checkbox to have Elderly Care services'),
                  secondary: Container(
                    height: 50,
                    width: 50,
                    child: Image.asset(
                      "assets/images/elderly_care.jpg",
                      fit: BoxFit.cover,
                    ),
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.0), // Optionally
                    side: const BorderSide(color: Colors.green),
                  ),
                  autofocus: false,
                  isThreeLine: true,
                  activeColor: Colors.blue,
                  checkColor: Colors.white,
                  selected: _valu3,
                  value: _valu3,
                  onChanged: (bool? value3) {
                    setState(() {
                      _valu3 = value3 ?? true;
                    });
                  },
                ),
              )),
        ),
      ]),
      ClipPath(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: 850,
          color: Colors.white,
          child: Column(
            children: [
              SizedBox(
                height: 150,
              ),
              Row(
                children: [
                  //Flexible(
                  //child:
                  SizedBox(
                    width: 500,
                  ),
                  //),
                  Flexible(
                    child: Center(
                      child: SizedBox(
                          width: 350,
                          child: DropdownSearch<String>.multiSelection(
                            items: items,
                            popupProps: PopupPropsMultiSelection.menu(
                              showSelectedItems: true,
                              disabledItemFn: (String s) => s.startsWith('I'),
                            ),

                            onChanged: (List<String> selectedValue) {
                              /*dropdownSelected =
                      selectedValue.isNotEmpty ? selectedValue[0] : '';*/
                              // print(selectedValue);
                              selectedValue1 = [...selectedValue];
                              print("SelectedValue1");
                              print(selectedValue1);
                            },
                            //selectedItems: items,
                          )),
                    ),
                  ),
                  Flexible(
                      child: SizedBox(
                    width: 25,
                  )),
                  Flexible(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Stack(
                        children: <Widget>[
                          Positioned.fill(
                            child: Container(
                              decoration: const BoxDecoration(
                                gradient: LinearGradient(
                                  colors: <Color>[
                                    Color(0xFF0D47A1),
                                    Color(0xFF1976D2),
                                    Color(0xFF42A5F5),
                                  ],
                                ),
                              ),
                            ),
                          ),
                          TextButton(
                            style: TextButton.styleFrom(
                              foregroundColor: Colors.white,
                              padding: const EdgeInsets.all(16.0),
                              textStyle: const TextStyle(fontSize: 15),
                            ),
                            onPressed: () {
                              setState(() {
                                updated = 1;
                              });
                            },
                            child: const Text('Refresh Table'),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Flexible(
                      child: SizedBox(
                    width: 25,
                  )),
                  Flexible(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: Stack(
                        children: <Widget>[
                          Positioned.fill(
                            child: Container(
                              decoration:
                                  const BoxDecoration(color: Colors.green),
                            ),
                          ),
                          TextButton(
                            style: TextButton.styleFrom(
                              foregroundColor: Colors.white,
                              padding: const EdgeInsets.all(16.0),
                              textStyle: const TextStyle(fontSize: 15),
                            ),
                            onPressed: () {
                              
                            },
                            child: const Text('Export to CSV'),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Flexible(
                child: SizedBox(
                  height: 40,
                ),
              ),
              Flexible(
                child: ListView.separated(
                  padding: const EdgeInsets.all(16.0),
                  itemCount: /*selectedValue1 == null ? 1 :*/
                      selectedValue1.length,
                  separatorBuilder: (BuildContext context, int index) =>
                      Divider(
                          height: 0,
                          indent: 180,
                          endIndent: 400,
                          color: Colors.grey),
                  itemBuilder: (BuildContext context, int index) {
                    if (index == 0) {
                      // return the header
                      return Container(
                        padding: EdgeInsets.all(16.0),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Flexible(
                                    child: SizedBox(
                                  width: 650,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Maid Name",
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Occupied Days",
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Occupied Dates",
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Age",
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Experience",
                                  style: TextStyle(
                                      fontSize: 18.0,
                                      fontWeight: FontWeight.bold),
                                ))),
                              ],
                            ),
                            Divider(
                                height: 30,
                                indent: 165,
                                endIndent: 385,
                                color: Colors.grey),
                            Row(
                              children: [
                                Flexible(
                                    child: SizedBox(
                                  width: 650,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  selectedValue1[index],
                                  style: TextStyle(fontSize: 18.0),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "Sunday",
                                  style: TextStyle(fontSize: 18.0),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "01/01/2023",
                                  style: TextStyle(fontSize: 18.0),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "18",
                                  style: TextStyle(fontSize: 18.0),
                                ))),
                                Flexible(
                                    child: SizedBox(
                                  width: 50,
                                )),
                                Flexible(
                                    child: Center(
                                        child: Text(
                                  "4 Years",
                                  style: TextStyle(fontSize: 18.0),
                                ))),
                              ],
                            )
                          ],
                        ),
                      );
                    } else {
                      return Container(
                          padding: EdgeInsets.all(16.0),
                          child: Row(
                            children: [
                              Flexible(
                                  child: SizedBox(
                                width: 650,
                              )),
                              Flexible(
                                  child: Center(
                                      child: Text(
                                selectedValue1[index],
                                style: TextStyle(fontSize: 18.0),
                              ))),
                              Flexible(
                                  child: SizedBox(
                                width: 50,
                              )),
                              Flexible(
                                  child: Center(
                                      child: Text(
                                "Sunday",
                                style: TextStyle(fontSize: 18.0),
                              ))),
                              Flexible(
                                  child: SizedBox(
                                width: 50,
                              )),
                              Flexible(
                                  child: Center(
                                      child: Text(
                                "01/01/2023",
                                style: TextStyle(fontSize: 18.0),
                              ))),
                              Flexible(
                                  child: SizedBox(
                                width: 50,
                              )),
                              Flexible(
                                  child: Center(
                                      child: Text(
                                "18",
                                style: TextStyle(fontSize: 18.0),
                              ))),
                              Flexible(
                                  child: SizedBox(
                                width: 50,
                              )),
                              Flexible(
                                  child: Center(
                                      child: Text(
                                "4 Years",
                                style: TextStyle(fontSize: 18.0),
                              ))),
                            ],
                          ));
                    }
                  },
                ),
              ),
            ],
          ),
        ),
        clipper: CustomClipPath(),
      ),
    ]);
  }
}

字符串
我真的是第一次尝试这个,我已经尝试了各种博客提供的大部分东西。但是,我无法实现它作为海事组织,按钮是上面的列表视图。真的需要你的帮助
多谢了!

lsmd5eda

lsmd5eda1#

下面是一个导出web和移动的设备csv的示例。您可以根据自己的喜好进行检查和修改。
Link to the output

  • 我创建了一个助手类来处理csv文件
import 'dart:convert';
import 'dart:html' as html;
import 'dart:io';
import 'package:csv/csv.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

class FileHelper {

  static void saveCSV(List<List<dynamic>> list) {
    if (kIsWeb) {
      webSaveCSV(list);
    } else {
      mobileSaveCSV(list);
    }
  }

  static void webSaveCSV(List<List<dynamic>> list) {
    try {
      String csvData = const ListToCsvConverter().convert(list);
      final bytes = utf8.encode(csvData);
      final blob = html.Blob([bytes]);
      final url = html.Url.createObjectUrlFromBlob(blob);
      final anchor = html.document.createElement('a') as html.AnchorElement..href = url..style.display = 'none'..download = 'myfile.csv';       
      html.document.body?.children.add(anchor);    
      anchor.click();
      html.Url.revokeObjectUrl(url);
    } catch (ex) {
      debugPrint('WEB_SAVE_CSV_EXCEPTION : $ex');
    }
  }

  static Future<void> mobileSaveCSV(List<List<dynamic>> list) async {
    try {
      String csvData = const ListToCsvConverter().convert(list);
      String directory = '';

      if (Platform.isIOS) {
        directory = (await getApplicationSupportDirectory()).path;
      } else {
        directory = (await getExternalStorageDirectory())!.absolute.path;
      }

      String filename = DateTime.now().toString();
      final path = '$directory/$filename.csv';
      final File file = File(path);
      
      await file.writeAsString(csvData).then((file) {
        print(file.path);
      });
      
    } catch(ex) {
      debugPrint('MOBILE_SAVE_CSV_EXCEPTION : $ex');
      return null;
    }
  }

}

字符串

  • 一个与您的屏幕类似的示例屏幕
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final datas = [
    ['Maid 1', 'Sunday', '01/01/2023', '18', '4 Years'],
    ['Maid 2', 'Sunday', '01/01/2023', '18', '4 Years'],
  ];

  @override
    void initState() {
      datas.insert(0, ['Maid Name', 'Occupied Days', 'Occupied Date', 'Age', 'Experience']);
      super.initState();
    }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          MaterialButton(
            color: Colors.green,
            onPressed: () {
              FileHelper.saveCSV(datas);
            },
            child: Text('Export CSV'),
          ),
          Expanded(
            child: ListView.separated(
              itemCount: datas.length,
              itemBuilder: (context, index) {
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text(datas[index][0]),
                    Text(datas[index][1]),
                    Text(datas[index][2]),
                    Text(datas[index][3]),
                    Text(datas[index][4]),
                  ],
                );
              },
              separatorBuilder: (context, index) {
                return Divider();
              },
            ),
          ),
        ],
      ),
    );
  }
}

相关问题