How To Dynamically Add Or Remove Items From A Listview In Flutter

admin_img Posted By Bajarangi soft , Posted On 02-11-2020

If you want to delete item from listview in flutter. With this solution you’ll still see the view change. If you want to prevent that, you’ll need a new stateful page, and a bit of refactoring: 1. Make your _saved items global (only for this example) 2. Remove the _pushSaved method 3. Update the onPressed function that used to call the _pushSaved function 4. Add the stateful DetailPage instead of the _pushSaved method

How To Dynamically Add Or Remove Items From A Listview In Flutter

Add Remove Items From A Listview
Complete Code For Add Remove Items From A Listview In Flutter
main.dart

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  TextEditingController _textController = TextEditingController();

  List<String> _listViewData = [
    "Swipe Right / Left to remove",
    "Swipe Right / Left to remove",
    "Swipe Right / Left to remove",
    "Swipe Right / Left to remove",
  ];

  _onSubmit() {
    setState(() {
      _listViewData.add(_textController.text);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Text('Add & Remove from ListView'),
      ),
      body: Column(
        children: <Widget>[
          TextField(
            controller: _textController,
            decoration: InputDecoration(
              hintText: 'enter text to add',
            ),
          ),
          SizedBox(height: 15.0),
          Center(
            child: RaisedButton(
              onPressed: _onSubmit,
              child: Text('Add to List'),
              color: Colors.green,
            ),
          ),
          Expanded(
            child: StreamBuilder<Object>(
              stream: null,
              builder: (context, snapshot) {
                return ListView(
                  scrollDirection: Axis.vertical,
                  padding: EdgeInsets.all(10.0),
                  children: _listViewData.reversed.map((data) {
                    return Dismissible(
                      key: Key(data),
                      child: ListTile(
                        title: Text(data),
                      ),
                    );
                  }).toList(),
                );
              }
            ),
          ),
        ],
      ),
    );
  }
}

Related Post