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

时间:2019-11-27 18:22:22

标签: csv flutter dart

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

问题是我的列表不生成行

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

enter image description here


我尝试了https://pub.dev/packages/csv#-readme-tab-Not viewing Table Layout from a csv in flutter,我已经阅读了多个csv文件 但是每次我都有同样的问题。

我在做什么错了?

请帮助新的开发人员。 ;)

1 个答案:

答案 0 :(得分:0)

您可以在下面复制粘贴运行完整代码
我在函数setState中添加了loadAsset()
我没有遇到列宽问题,如果您仍然遇到此问题,请尝试添加第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不能显示正确的绿色,
所以我将最终结果粘贴到第二张图片中

enter image description here

enter image description here

完整代码

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(),
        ),
      ),
    );
  }
}