Flutter函数在构建中被无限调用

时间:2019-05-26 08:58:52

标签: flutter dart

我正在制作一个加载CSV并在屏幕上显示表格的应用程序,但是在构建状态下无限调用加载函数,有人知道如何修复它,我只想调用一次,但是我的代码调用了很多时间。

这是控制台屏幕截图: a busy cat

代码如下:

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

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

  List<List<dynamic>> data = [];

  loadAsset() async {
    final myData = await rootBundle.loadString("asset/dreamss.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);

    return csvTable;
  }
  void load() async{
    var newdata = await loadAsset();
    setState(() {
      data = newdata;
    });
    print("am i still being called called ");
  }

  @override
  Widget build(BuildContext context) {

    load();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Apps"),),
        //floatingActionButton: FloatingActionButton( onPressed: load,child: Icon(Icons.refresh),),
        body: ListView(
          children: <Widget>[
            Container(margin: EdgeInsets.only(top: 20.0),),
        Table(
          border: TableBorder.all(width: 1.0,color: Colors.black),
          children: data.map((item){
            return TableRow(
              children: item.map((row){
                return Text(row.toString(),style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.w900),);
              }).toList(),
            );
          }).toList(),
        ),
    ]),
    ));
  }
}

1 个答案:

答案 0 :(得分:1)

这是解决方案。

@override
void initState() {
  super.initState();
  load(); // use it here
}


@override
Widget build(BuildContext context) {
  return MaterialApp(...); // no need to call initState() here
}