Flutter - How can the App Automatically Add List Tiles?

194 Views Asked by At

I am new to flutter and have a specific question.

What methods would be able to add a list tile to an existing page as a result of a periodic timeline?

For example: The app will add a new list tile to the screen every 15 minutes.

Any advice on how to achieve this output would be very much appreciated!

1

There are 1 best solutions below

0
On

first you need a timer to make a periodical update to your layout:

 Timer? timer;
  void initState() {
    super.initState();
    timer =
        Timer.periodic(Duration(seconds: 1), (Timer t) => updatePeriodically());
  }
 @override
   void dispose() {
     timer?.cancel();
     super.dispose();
   }

then you need to assign a new value to your list builder every time your periodical function is called:

  void updatePeriodically() {
    setState(() {
      itemsCount += 1;
    });
  }

the full example code:

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  @override
  Timer? timer;
  void initState() {
    super.initState();
    timer =
        Timer.periodic(Duration(seconds: 1), (Timer t) => updatePeriodically());
  }

  int itemsCount = 3;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: itemsCount,
        itemBuilder: (context, index) {
          return ListTile(
            leading: Text("item" + index.toString()),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  void updatePeriodically() {
    setState(() {
      itemsCount += 1;
    });
  }
}