API中动态复选框x的Flutter列表

w8f9ii69  于 2023-01-18  发布在  Flutter
关注(0)|答案(1)|浏览(137)

我是一个初学者和新的Flutter。我想帮助以下我需要得到一个列表的项目与复选框从和API我应该能够选择一个或多个复选框
如果我选中一个复选框,它应该显示所选的总金额。如果我选中两个复选框,它应该为我计算两个复选框的总和并显示它。
以下是我目前所做的工作。

我将非常感谢您的解决方案
这是我代码

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:liquid_pull_to_refresh/liquid_pull_to_refresh.dart';
import 'dart:convert';
import 'dart:ffi';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:stachup/models/TeamModel.dart';
import 'package:stachup/models/newStaches.dart';
import 'package:stachup/models/TeamModel.dart';

class Stash extends StatefulWidget {
  String first_name;
  String token;
  String referalcode;
  String last_name;

  Stash(
      {Key? key,
      required this.first_name,
      required this.token,
      required this.last_name,
      required this.referalcode})
      : super(key: key);

  @override
  State<Stash> createState() => _StashState();
}

class _StashState extends State<Stash> {
  bool isChecked = false;
  String? first_name;
  String? token;
  String? last_name;
  String? referalcode;

  bool setup = false;
  String? setupError;

  bool _isChecked = false;

  late SharedPreferences logindata;
  userData() async {
    logindata = await SharedPreferences.getInstance();
    first_name = logindata.getString('first_name')!;
    last_name = logindata.getString('last_name')!;
    referalcode = logindata.getString('referalcode')!;
    token = logindata.getString('token')!;
    setState(() {});
  }

  List<Team> teams = [];
  Future getData() async {
    var response = await http.get(Uri.https(
        'incoming.isplitpay.com', 'api/durationlist', {'token': token}));
    var jsonData = jsonDecode(response.body);
    print(token);

    for (var eachTeam in jsonData) {
      var datetime = DateTime.parse(eachTeam["paid_date"]);
      final team = Team(
        id_pes: eachTeam['id_pes'],
        amount: eachTeam['amount'],
        paid_date: datetime,
      );
      teams.add(team);
    }
    // print(teams.length);
  }

  @override
  void initState() {
    super.initState();
    userData();
  }

  @override
  Widget build(BuildContext context) {
    //getData();
    return Scaffold(
      backgroundColor: Colors.blue.shade50,
      body: FutureBuilder(
        future: getData(),
        builder: ((context, snapshot) {
          //if done loading show data
          if (snapshot.connectionState == ConnectionState.done) {
            return Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
              ),
              child: ListView.builder(
                  itemCount: teams.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Container(
                        height: 80,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.white,
                          ),
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Checkbox(
                              checkColor: Colors.white,
                              value: _isChecked,
                              onChanged: (bool? value) {
                                setState(() {
                                  _isChecked = value!;
                                });
                                print(value);
                              },
                            ),
                            Text(
                              'GHS ' + teams[index].amount,
                              style: GoogleFonts.lato(
                                fontSize: 16,
                              ),
                            ),
                            Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 20.0),
                                  child: Text(
                                    'Savings for',
                                    style: GoogleFonts.lato(
                                      fontSize: 16,
                                    ),
                                  ),
                                ),
                                Text(
                                  "${teams[index].paid_date.day.toString().padLeft(2, '0')}-${teams[index].paid_date.month.toString().padLeft(2, '0')}-${teams[index].paid_date.year}",
                                  style: GoogleFonts.lato(
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  }),
            );

//else show circule progress bar
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        }),
      ),
    );
  }
}

My Model
import 'package:flutter/material.dart';

class Team {
  final String id_pes;
  final String amount;
  final DateTime paid_date;

  Team({
    required this.id_pes,
    required this.amount,
    required this.paid_date,
  });
}

class UserProgress {
  final int goaldays;
  final double progress;

  UserProgress({
    required this.goaldays,
    required this.progress,
  });
}
tkclm6bt

tkclm6bt1#

  • 您可以在类团队中添加变量来控制CheckBox。
  • 选中的列表可以通过List.where()函数过滤出来。
  • 我添加了Tooltip()小部件来显示预期效果。
import 'package:flutter/material.dart';

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  List<Team> dataList = [
    Team(id_pes: '1', amount: '10', paid_date: DateTime.now()),
    Team(id_pes: '2', amount: '20', paid_date: DateTime.now()),
    Team(id_pes: '3', amount: '30', paid_date: DateTime.now()),
    Team(id_pes: '4', amount: '40', paid_date: DateTime.now()),
    Team(id_pes: '5', amount: '50', paid_date: DateTime.now()),
    Team(id_pes: '6', amount: '60', paid_date: DateTime.now()),
   
  ];

  Widget _buildListItem(int index) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: Container(
        height: 80,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.white,
          ),
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Checkbox(
              checkColor: Colors.white,
              value: dataList[index].isChecked ?? false,
              onChanged: (bool? value) {
                setState(() {
                  dataList[index].isChecked = value;
                });
                print(value);
              },
            ),
            Text(
              'GHS ' + dataList[index].amount,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var checkedList = dataList.where((data) => data.isChecked ?? false);
    var totalAmount = checkedList.isNotEmpty
        ? 'TotalAmount:${checkedList.reduce((before, after) => Team(amount: '${double.parse(before.amount) + double.parse(after.amount)}', id_pes: '_', paid_date: DateTime.now())).amount} '
        : '';
    return Scaffold(
        body: ListView.builder(
            shrinkWrap: true,
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              return Tooltip(
                  message: totalAmount, child: _buildListItem(index));
            }));
  }
}

class Team {
  final String id_pes;
  final String amount;
  final DateTime paid_date;
  bool? isChecked;

  Team({
    required this.id_pes,
    required this.amount,
    required this.paid_date,
    this.isChecked,
  });
}

相关问题