how to refresh ListView.builder flutter
Asked Answered
W

3

8

How can I refresh my ListView.builder when adding item to the list?

ListView.builder(
      itemCount: propList.length,
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      itemBuilder: (context,index)=> Text(propList[index]),
    )

my button is

FlatButton(onPressed: (){propList.add('text');}, child: Text('add'))
Winy answered 27/1, 2020 at 8:40 Comment(0)
C
14

Assuming you've extended the StatefulWidget, you must call setState everytime you change the state. Ex:

setState(() { propList.add('text'); });

Here's a quick example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) => MaterialApp(home: MyList());
}

class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State<MyList> {
  List<String> propList = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My List'),
      ),
      body: ListView.builder(
        itemCount: propList.length,
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemBuilder: (context,index)=> Text(propList[index]),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() => propList.add('text')),
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
Chretien answered 27/1, 2020 at 8:58 Comment(5)
thank you a lots, that worked, and thank you to make it with an example.Winy
what about deleting? setState(() { propList.remove(widget.propName); }); that didn't workWiny
remove method takes the exact object that you want to remove. Or you can call removeLast() @HusamuldeenChretien
how can Force Refresh be done on STATELESS widget..Virtuosity
@VrajendraSinghMandloi You can use provider package and use future builder. Wrap ListView builder in CosumerMandell
S
1

You can try: onPressed: setState(() { propList.length; });

Sultan answered 18/1, 2022 at 12:55 Comment(0)
S
0

Here I've created flat_list widget which has similar specifications as in React Native's FlatList. Below will simply work.

FlatList(
  onRefresh: () async {
    await Future.delayed(const Duration(seconds: 2));
  },
  data: items.value,
  buildItem: (item, index) {
    var person = items.value[index];

    return ListItemView(person: person);
  },
),
Strontianite answered 12/11, 2022 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.