将数据从csv转换为动态列表(Flutter)

8e2ybdfx  于 2023-01-10  发布在  Flutter
关注(0)|答案(3)|浏览(142)

我创建了一个加载CSV文件并将其显示为列表视图的应用程序,我使用了以下示例。https://gist.github.com/Rahiche/9b4b2d3b5c24dddbbe662b58c5a2dcd2
问题是我的List不生成行

I/flutter ( 2158): [[M01, Plastics, 50, NA
I/flutter ( 2158): M02, Plastics, 85, NA
I/flutter ( 2158): M03, Wood, 50, NA
I/flutter ( 2158): M04, Wood, 15, 3
I/flutter ( 2158): M05, Plastics, 50, NA]]

下面是我的代码

class TableLayout extends StatefulWidget {
  @override
  _TableLayoutState createState() => _TableLayoutState();
}

class _TableLayoutState extends State<TableLayout> {
  List<List<dynamic>> data = [];
  loadAsset() async {
    final myData = await rootBundle.loadString("assets/ford.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
    print(csvTable);
    data = csvTable;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: () async {
            await loadAsset();
            //print(data);
          }),
      appBar: AppBar(
        title: Text("Table Layout and CSV"),
      ),

      body: SingleChildScrollView(
        child: Table(
          columnWidths: {
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(200.0),
          },
          border: TableBorder.all(width: 1.0),
          children: data.map((item) {
            return TableRow(
                children: item.map((row) {
                  return Container(
                    color:
                    row.toString().contains("NA") ? Colors.red : Colors.green,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        row.toString(),
                        style: TextStyle(fontSize: 20.0),
                      ),
                    ),
                  );
                }).toList());
          }).toList(),
        ),
      ),
    );
  }
}

和我的ford.csv

M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA

--- i tried the hints from https://pub.dev/packages/csv#-readme-tab- and from Not viewing Table Layout from a csv in flutter and I have read several csv files but every time i have the same issues.
我到底做错了什么?
请帮助一位新的Flutter研制人员。)

vq8itlhq

vq8itlhq1#

你可以复制粘贴运行下面的完整代码
我在函数loadAsset()中添加了setState
我没有遇到列宽问题,如果您仍然有此问题,请尝试添加列2、3或缩小FixedColumnWidth的宽度

columnWidths: {
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(100.0),
            2: FixedColumnWidth(50.0),
          },

代码片段

loadAsset() async {
    final myData = await rootBundle.loadString("assets/ford.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
    print(csvTable);
    data = csvTable;
    setState(() {

    });
  }

工作演示
动画GIF没有显示正确的绿色,
所以我把最终结果粘贴到第二张图片中

全码

import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: TableLayout(),
    );
  }
}

class TableLayout extends StatefulWidget {
  @override
  _TableLayoutState createState() => _TableLayoutState();
}

class _TableLayoutState extends State<TableLayout> {
  List<List<dynamic>> data = [];
  loadAsset() async {
    final myData = await rootBundle.loadString("assets/ford.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
    print(csvTable);
    data = csvTable;
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.refresh),
          onPressed: () async {
            await loadAsset();
            //print(data);
          }),
      appBar: AppBar(
        title: Text("Table Layout and CSV"),
      ),

      body: SingleChildScrollView(
        child: Table(
          columnWidths: {
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(200.0),
          },
          border: TableBorder.all(width: 1.0),
          children: data.map((item) {
            return TableRow(
                children: item.map((row) {
                  return Container(
                    color:
                    row.toString().contains("NA") ? Colors.red : Colors.green,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        row.toString(),
                        style: TextStyle(fontSize: 20.0),
                      ),
                    ),
                  );
                }).toList());
          }).toList(),
        ),
      ),
    );
  }
}
xpszyzbs

xpszyzbs2#

这是因为不同的EOL(行结束)字符用于终止文件中的一行。即一些程序使用'\r\n'而其他'\n'。
因此,要解决这个问题,你必须考虑到。即我正在使用csv包在windows操作系统上,而从csv文件阅读,你应该指定eol参数CsvToListConverter()convert方法。

return CsvToListConverter().convert(csv.data, eol: '\n');
z8dt9xmd

z8dt9xmd3#

fast_csv解析器用于解析CSV数据。
它比csv解析器快2.9 - 4.7倍。
如果您需要解析大量的数据,那么它会更有效率。
行尾为\n\r\n\r(无需配置)。

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final res = _fast_csv.parse(_csv);
  print(res);
}

final _csv = '''
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
''';

输出:

[[M01, Plastics, 50, NA], [M02, Plastics, 85, NA], [M03, Wood, 50, NA], [M04, Wood, 15, 3], [M05, Plastics, 50, NA]]

相关问题