Home > OS >  How to make Dynamic checkbox with Api data?
How to make Dynamic checkbox with Api data?

Time:06-20

How to make using Listview.builder() and handle it click in flutter

CodePudding user response:

Simple way to achieve your goal, try this

import 'package:flutter/material.dart';

class SimpleTest extends StatefulWidget {
  const SimpleTest({Key? key}) : super(key: key);

  @override
  State<SimpleTest> createState() => _SimpleTestState();
}

class _SimpleTestState extends State<SimpleTest> {
  List<int> selectedItem = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
              child: ListView.builder(
                  itemCount: 8,
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    return Container(
                      padding: const EdgeInsets.all(8.0),
                      child: Row(
                        children: [
                          Expanded(
                            child: CheckboxListTile(
                              title: Text("Check Box$index"),
                              value: selectedItem.contains(index) ? true : false,
                              onChanged: (newValue) {
                                if (selectedItem.contains(index)) {
                                  selectedItem.remove(index);
                                } else {
                                  selectedItem.add(index);
                                }
                                setState(() {});
                              },
                              controlAffinity: ListTileControlAffinity.leading, //  <-- leading Checkbox
                            ),
                          )
                        ],
                      ),
                    );
                  }))
        ],
      ),
    );
  }
}
  • Related