Flutter Trouble with multiselect checkboxes - data

2019-07-22 17:15发布

问题:

The following code displays the items listed in my collection (Firestore) I am attempting to create the ability to check any item(s) and then have those items store into a "Favorites" on the next screen.

Currently, the checkboxes are an all or nothing. Either all items are unchecked or checked once tapped.

class _SelectScreenState extends State<SelectScreen> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Select Exercises')),
      body: _buildBody(context),
    );
   }

   Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('exercises').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();

        return _buildList(context, snapshot.data.documents);
      },
    );
   }

   Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) 
   {
    return ListView(
      padding: const EdgeInsets.only(top: 20.0),
      children: snapshot.map((data) => _buildListItem(context, 
   data)).toList(),
    );
  }

   Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = Record.fromSnapshot(data);

    return Padding(
      key: ValueKey(record.name),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: ListTile(
          title: Text(record.name),
          trailing: Checkbox(
            value: _isChecked,
            onChanged: (bool value) {
            setState(() {
              _isChecked = value;
            });
          },
          )
        ),
        ),
       );
     }
    }

    class Record {
    final String name;
    final DocumentReference reference;

    Record(this.name, this.reference);

    Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        name = map['name'];

   Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

    @override
    String toString() => "Record<$name:>";
    }

回答1:

It is because you are making use of a single variable for all the checkboxes.

To fix that you could create a dedicated stateful widget, which would handle the state of each of the checkbox's separately from the rest.

So you could replace your ListTile with something like

Exercise(
 title: record.name,
)

and then you could define the Exercise widget as follows

class Exercise extends StatefulWidget {
  final String title;

  Exercise({this.title});

  @override
  _ExerciseState createState() => _ExerciseState();
}

class _ExerciseState extends State<Exercise> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(widget.title),
      trailing: Checkbox(
          value: selected,
          onChanged: (bool val) {
            setState(() {
              selected = val;
            });
          }),
    );
  }
}

Here is a complete working example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          Exercise(
            title: "Exercises 1",
          ),
          Exercise(
            title: "Exercises 2",
          ),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class Exercise extends StatefulWidget {
  final String title;

  Exercise({this.title});

  @override
  _ExerciseState createState() => _ExerciseState();
}

class _ExerciseState extends State<Exercise> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(widget.title),
      trailing: Checkbox(
          value: selected,
          onChanged: (bool val) {
            setState(() {
              selected = val;
            });
          }),
    );
  }
}



回答2:

Because you have a global variable _isChecked, this needs to be created with each listTile.

Try moving the variable

Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = Record.fromSnapshot(data);
    bool _isChecked = false; //try moving it here

    return Padding(
      key: ValueKey(record.name),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: ListTile(
          title: Text(record.name),
          trailing: Checkbox(
            value: _isChecked,
            onChanged: (bool value) {
            setState(() {
              _isChecked = value;
            });
          },
          )
        ),
        ),
       );
     }