Home > Enterprise >  The ListView outputs the dataList 2 times
The ListView outputs the dataList 2 times

Time:09-27

When I run the flutter application, ListView outputs the values (0 to 999) 2 times. Maybe I'm calling the a () method in the wrong place? I know it is possible to use the StateLessWidget, but I want it to be StatefulWidget.

import 'package:cctracker/CCData.dart';
import 'package:flutter/material.dart';

class CCList extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return CCListState();
  }
}

class CCListState extends State<CCList> {

  List<CCData> data = [];
  void a() {
    for (var i = 0; i < 1000; i  ) {
      data.add(CCData(name: 'Name', symbol: i.toString(), rank: 1, price: 600000));
    }
  }

  @override
  Widget build(BuildContext context) {
    a();
    return Scaffold(
      appBar: AppBar(
        title: Text('CC Tracker'),
      ),
      body:Container(
          child: ListView(
            children: _buildList(),
          )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => {},
        child: Icon(Icons.refresh),
      ),
    );
  }

  List<Widget> _buildList() {
    return data.map((e) => ListTile(
      subtitle: Text(e.symbol),
      title: Text(e.name),
      leading: CircleAvatar(child: Text(e.rank.toString()),),
      trailing: Text('\$${e.price.toString()}'),
    )).toList();
  }
}

CodePudding user response:

You add 1000 items to your list every time build() is called. You should rather call this in initState().

@override
  void initState() {
     super.initState();
     a();
  }

In general, you should use ListView.builder() instead of building the whole list of widgets with _buildList().

CodePudding user response:

Call the method 'a' inside the initState method like below. This should solve your problem. The initState method only called once while initializing the initial state. Now if you need to update the data. Just update it and then call the setState() method to show the updated result.

class CCListState extends State<CCList> {

  List<CCData> data = [];
  void a() {
      for (var i = 0; i < 1000; i  ) {
      data.add(CCData(name: 'Name', symbol: i.toString(), rank: 1,price:600000));
  }


  @override
  void initState() {
     super.initState();
     a();
  }

  //rest of the codes...
}
  • Related