Checkbox in the Flutter

Asked

Viewed 836 times

0

I’m trying to create a List, which shows the necessary ingredients, and next to them, a Checkbox, simulating what the user took or not. I tried Checkbox, Checkboxlisttile, but I have no idea what to do. The checkbox only needs to change from 'unchecked' to 'checked'. I’m using a Statefulwidget.

 class CheckboxClasse extends StatefulWidget {
      @override
      _CheckboxState createState() => _CheckboxState();
    }

    class _CheckboxState extends State<CheckboxClasse> {
      bool isCheck = false;
      List<Meal> meal;

      @override
      Widget build(BuildContext context) {
        return ListTile(
            title: new Row(children: <Widget>[
          new CheckboxListTile(
            value: isCheck,
            onChanged: (bool newValue) {
              setState(() {
                isCheck = newValue;
              });
            },
            activeColor: Colors.pink,
            checkColor: Colors.green,
          ),
        ]));
      }
    }
  • If I understand your code correctly, there are points to be considered... The ListTile() was created to present information in an organized and beautiful way and works well. The CheckboxListTile() is a variation of ListTile... understanding this, what reason made you put a CheckboxListTile within a Row which in turn is inside a ListTile?... Tried to use only the CheckboxListTile and fill in the attributes he has?

  • I haven’t tried, but I’ll try now! It’s just that I’m trying to show a list, which is in another class, but I can’t call 'Meal.ingredientes', which is the list that will have the checkbox on the side, I tried to use a '.Tolist()' and '.Tostring()', but I have no idea what to do...

  • I answered an example of using a list with a check and can run it on the same dartpad... before what you presented code was what gave to guide... in case it is not enough, edit your question and put the full code of the application and so it will be possible to analyze what is happening.

2 answers

1


I recommend you study the documentation of the components Listtile and Checkboxlisttile to better understand how they work. Remember that they were created only to facilitate the implementation of useful components that are used in numerous apps. In his case it is noted that he did not perform the basic tests of each one alone exploiting its properties.

No need to insert a CheckboxListTile within a ListTile. The CheckboxListTile was already created to show the check, he was born for it. In this example all you need is it.

I have put together an example that can be analyzed by you in order to understand how it works.

Example

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final itens = <Map>[
    {"nome": "Arroz", "check": false},
    {"nome": "Feijão", "check": false},
    {"nome": "Macarrão", "check": false},
    {"nome": "Leite", "check": false},
  ];
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: itens.length,
      itemBuilder: (ctx, index) {
        return CheckboxListTile(
          title: Text(itens[index]["nome"]),
          subtitle: Text(
            "Este item ${itens[index]["check"] ? "" : "não"} está selecionado",
          ),
          value: itens[index]["check"],
          onChanged: (newValue) {
            setState(() {
              itens[index]["check"] = newValue;
            });
            print(
              "Mudou check da palavra ${itens[index]["nome"]} para: $newValue",
            );
          },
        );
      },
    );
  }
}

This code can be copied and pasted on Dartpad. I recommend that you use it a lot to create examples and understand the behaviors of each component that is already offered ready to use.

-1

I managed to use Checkbox according to your tips, I really appreciate it. Now I just need to call the class in the widget I want, but the error in Card(). Is it because of a stateful being and the class I’m going to make Checkbox call is stateless?

Follows the code.

//Imports

class Mealdetailscreen extends Statelesswidget { @override Widget build(Buildcontext context) { final Meal = Modalroute.of(context).settings.Arguments as Meal;

return Scaffold(
    appBar: AppBar(
      title: Text(meal.title),
    ),
    body: SingleChildScrollView(
        child: Column(
        children: <Widget>[
          Container(
            height: 300,
            width: double.infinity,
            child: Image.network(
              meal.imageUrl,
              fit: BoxFit.cover,
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(vertical: 10),
            child: Text('Ingredientes', style: Theme.of(context).textTheme.title),
          ),
          Container(
            width: double.maxFinite,
            height: 400,
            child: ListView.builder(
              itemCount: meal.ingredientes.length,
              itemBuilder: (context, index){
              return Card(
                CheckboxClasse(),  //classe Stateful
                child: Text(meal.ingredientes[index], 
                style: TextStyle(fontSize: 18)),
                color: Colors.red[50],
                elevation: 5,
               );
            }),
          ),

            ],
          ),
        ));
  }
}
//-----------------------------------------------------------------------

class CheckboxClasse extends StatefulWidget {
  @override
  _CheckboxState createState() => _CheckboxState();
}

class _CheckboxState extends State<CheckboxClasse> {
  // void changeBox(bool valorzim) => setState(() => changedBox = valorzim);
  final List<Meal> meal = new List<Meal>();
  bool changedBox = false;

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      value: changedBox,
      onChanged: (bool valCheck) {
        setState(() {
          changedBox = valCheck;
        });
      },
    );
  }
}
  • 1

    If the problem of the original question has been solved flag as valid answer. As something else came up that is not the main question open a new question. It is also important to note that Stack follows a pattern of focus on specific problems and it is not recommended that replicas and rejoinders be made in a post, if you want to make any comment use the question or answer comment itself. Always try to follow the rules of the platform not to receive negative votes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.