Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter function called infinitely in build

Tags:

flutter

dart

I am making an app which loads the CSV and show the table on the screen but the load function is being called infinitely in the build state can anyone know how to fix it I wanted to call only once but my code called it many times.

Here is the console screenshot: a busy cat

Here is the code:

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

like image 213
Abhijit leihaorambam Avatar asked Sep 03 '25 17:09

Abhijit leihaorambam


1 Answers

Here is the solution.

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


@override
Widget build(BuildContext context) {
  return MaterialApp(...); // no need to call initState() here
}
like image 51
CopsOnRoad Avatar answered Sep 06 '25 19:09

CopsOnRoad