How To Use Dynamically Add Checkbox Using Flutter

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

There are two ways to create a widget in Flutter, first one is using Static data and other is Using dynamic content. We are using MAP data type in current tutorial to create multiple checkbox. Map is collection of data in Key – Value pairs. The data from Map can be easily accessible via its associated key. We would create a Map array with String and Boolean data. String is the name of Checkbox and Boolean is used to determine which checkbox is checked or not.

How To Use Dynamically Add Checkbox Using Flutter

Dynamically Add Checkbox
Complete Code Dynamically Add Checkbox For In

import 'package:flutter/material.dart';

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  List<int> _list = [1, 2, 3, 4, 5, 6 ,7, 8];
  bool _isChecked = true;

  _onPressed() {
    int count = _list.length;
    setState(() {
      _list.add(count + 1);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
          title: Text("Dynamically Add Checkbox"),
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: RaisedButton(
              onPressed: _onPressed,
              child: Text("Add CheckBox"),
              color: Colors.green,
              textColor: Colors.white,
            ),
          ),
          Column(
            children: _list
                .map((t) => CheckboxListTile(
              activeColor: Colors.green,
              title: Text("$t"),
              value: _isChecked,
              onChanged: (val) {
                setState(() {
                  _isChecked = val;
                });
              },
            ))
                .toList(),
          ),
        ],
      ),
    );
  }
}

Related Post