Dhanraj Nimbalkar
Dhanraj Nimbalkar

Reputation: 85

How to filter and update ListViewBuilder in Flutter?

    {
    "data": [
        {
            "title": "Asignment 1 ",
            "status": true,
            "date" : "7/18/2020"
        },
        {
            "title": "Asignment 2 ",
            "status": false,
            "date" : "7/18/2020"
        },
        {
            "title": "Asignment 2 ",
            "status": false,
            "date" : "7/18/2020"
        }
    ]
}


This is the data I am getting from API.


@override
  void initState() {
    _allTaskModel =
        API_Manager().getAllTasksofUser(firebaseAuth.currentUser.uid);

    super.initState();
  }

 @override
  // Widget projectWidget() {
  Widget build(BuildContext context) {
    return FutureBuilder<AllTasksModel>(
      future: _allTaskModel,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          if (snapshot.data.response.data.length > 0) {
            return ListView.builder(
                itemCount: snapshot.data.response.data.length,
                itemBuilder: (context, index) {
                  // UserDetailsModel userDetails = snapshot.data[index];
                  var tasks = snapshot.data.response.data[index];
                  return cardWidget(tasks);
                });
          } else
            return Container(
                child: Center(
              child: Text('No Task found'),
            ));
        } else {
          try {
            if (snapshot.data.response.data.length == 0) {
              return Container(
                  child: Center(
                child: Text('No Task found'),
              ));
            }
          } catch (e) {
            return Center(child: CircularProgressIndicator());
          }
        }
      },
    );
  }


this my code.cardWidget() basically returns Widget which contains data of task. I want to Filter the listView as Complete or incomplete according to status using SpeedDial buttons. When I click the Incomplete button from SpeedDial FloatingActionButtons then want to get a List of Incompleted Tasks. How can I apply the filter and update the List?

Upvotes: 0

Views: 516

Answers (1)

Andrej
Andrej

Reputation: 3225

If I understand you correctly, you load that from an api and you want to have a button that when clicked shows only the incomplete tasks. If yes then you can do something like this:

import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(),
    );
  }
}

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

class _HomeState extends State<Home> {
  final tasks = {
    "data": [
      {"title": "Asignment 1 ", "status": true, "date": "7/18/2020"},
      {"title": "Asignment 2 ", "status": false, "date": "7/18/2020"},
      {"title": "Asignment 2 ", "status": false, "date": "7/18/2020"}
    ]
  };

  bool showOnlyIncomplete = false; // the value that controls which tasks will be shown
  
  // this function toggles the showOnlyIncomplete value between false and true when 
  // clicked
  void toggleShowOnlyIncomplete() =>
      setState(() => showOnlyIncomplete = !showOnlyIncomplete);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          ElevatedButton(
            child: showOnlyIncomplete ? Text('Show all') : Text('Show only incomplete'),
            onPressed: () => toggleShowOnlyIncomplete(),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: tasks['data'].length,
              itemBuilder: (context, index) {
                final task = tasks['data'][index];
                
                // If we only want to show incompleted tasks and the current task
                // is done we show an empty Container
                if (showOnlyIncomplete && task['status'])
                  return Container();

                return ListTile(
                  title: Text('${task['title'] ?? 'Unknown'}'),
                  subtitle: Text('${task['date'] ?? 'Unknown'}'),
                  trailing:
                      task['status'] ? Icon(Icons.check) : Icon(Icons.close),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Upvotes: 1

Related Questions