Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to refresh ListView.builder flutter

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'))
like image 939
Husamuldeen Avatar asked Jan 27 '20 08:01

Husamuldeen


1 Answers

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.
    );
  }
}
like image 90
Manish Avatar answered Oct 22 '22 05:10

Manish