flutter 如何在两个数据库之间浮动时从sql数据库中取数据?

az31mfrm  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(120)

在flutter和sqflite中,我创建了这个函数来计算colPrix中的总价格。我想计算两个日期(周期时间)之间的总价格,每次想计算总价格时,我应该怎么做?
1/函数计算数据库中的Total(我在其中创建数据库)。

class DatabaseHelper {
  static DatabaseHelper _databaseHelper; // Singleton DatabaseHelper
  static Database _database; // Singleton Database

  String clientTable = 'client_table';
  String colId = 'id';
  String colNumerotelephone = 'numerotelephone';
  String colCode = 'code';
  String colPrix = 'prix';
  String colPriority = 'priority';
  String colColor = 'color';
  String colDate = 'date';

  DatabaseHelper._createInstance(); 

  factory DatabaseHelper() {
    if (_databaseHelper == null) {_databaseHelper = DatabaseHelper._createInstance(); // This is executed only once, singleton object}
    return _databaseHelper;
  }

  Future<Database> get database async {
    if (_database == null) { _database = await initializeDatabase();}
    return _database;
  }
.....
.....

  Future claculTotalPeriod (String startDate, String endDate) async {
    var totalClientperiod = await database;
    var result = await totalClientperiod.rawQuery("SELECT SUM($colPrix) AS TOTAL from $clientTable WHERE $colDate BETWEEN '$startDate' AND '$endDate'");
    return result.toList();
  }
}

2/显示结果

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

  @override
  State<StatefulWidget> createState() {
    return ClientListState();
  }
}

class ClientListState extends State<ClientList> {

  DatabaseHelper databaseHelper = DatabaseHelper();
  List<Client> clientList;

  int count = 0;
  int axisCount = 2;

  double somme_period = 00;
  String somme_total_period = "00.00";

  String startDate='';
  String endDate='';

  TextEditingController startdate = TextEditingController();
  TextEditingController finishdate = TextEditingController();

  void calcul_total_period() async {
    var total_sum_period = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['$startDate''$endDate'];
    setState(() {
      somme_period = total_sum_period ?? 00;
      somme_total_period = somme.toStringAsFixed(2);
    });
  }

  @override
  Widget build(BuildContext context) {

    if (clientList == null) {
      clientList = [];
      updateListView();
    }

 

    return Scaffold(
      appBar: myAppBar(),
      body: clientList.isEmpty
          ? Container(
              color: Colors.white,
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text('add+',
                      style: Theme.of(context).textTheme.bodyText2),
                ),
              ),
            )
          : Container(
              color: Colors.white,
              child: getClientsList(),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          navigateToDetail(Client('', '', '', 3, 0, 0.0), 'new');
        },
        tooltip: 'add',
        shape: const CircleBorder(
            side: BorderSide(color: Colors.black, width: 2.0)),
        child: const Icon(Icons.add, color: Colors.black),
        backgroundColor: Colors.white,
      ),
      bottomNavigationBar: OutlinedButton(
          onPressed: () {
    
            showDialog(
         ...
                      child: Column(
                      
                         TextField(
                                    controller: startdate,
                       
                                    decoration: const InputDecoration(
                                        icon: Icon(Icons.calendar_today
                                    ),
                               
                                    onTap: () async {
                                      DateTime pickedDate = await showDatePicker(
                                          context: context,
                                          initialDate: DateTime.now(),
                                          firstDate: DateTime(2022,12),
                                          lastDate: DateTime(2026,12));
                                      if (pickedDate != null) {
                                        print(
                                            pickedDate); 
                                        String formattedDate =
                                        DateFormat('yyyy-MM-dd').format(pickedDate);
                                        print(
                                            formattedDate); //formatted date output using intl package =>  2021-03-16
                                        setState(() {
                                          startdate.text =
                                              formattedDate;
                                          startDate = startdate.text.toString();
                                     
                                        });
                                      } else {}
                                    },
                                  ),
                        const SizedBox(height: 20,),
                        TextField(
                          controller: finishdate,
                        
                          decoration: const InputDecoration(
                              icon: Icon(Icons.calendar_today), //icon of text field
                  
                          ),
                        
                          onTap: () async {
                            DateTime pickedDate = await showDatePicker(
                                context: context,
                                initialDate: DateTime.now(),
                                firstDate: DateTime(2022,12),
                                lastDate: DateTime(2026,12));
                            if (pickedDate != null) {
                              print(
                                  pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                              String formattedDate =
                              DateFormat('yyyy-MM-dd').format(pickedDate);
                              print(
                                  formattedDate); //formatted date output using intl package =>  2021-03-16
                              setState(() {
                                finishdate.text =
                                    formattedDate; //set output date to TextField value.
                                endDate =  finishdate.text.toString();
                            
                              });
                            } else {}
                          },
                        ),
                          const SizedBox(height: 20,),
                          OutlinedButton(
                              onPressed: () {
                                calcul_total_period();
                              },
                              child: const Text(' total in period')),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              somme_total_period,
                              style: Theme.of(context).textTheme.headline5,
                              textAlign: TextAlign.center,
                            ),
                          ),


                        ],
                      ),
                    ),
                  );
                });
          },
          child: const Text('total')),
    );
  }

  Widget getClientsList() {
    return StaggeredGridView.countBuilder(
      physics: const BouncingScrollPhysics(),
      crossAxisCount: 4,
      itemCount: count,
      itemBuilder: (BuildContext context, int index) => GestureDetector(
        onTap: () {
          navigateToDetail(clientList[index], 'edit');
        },
       
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
                color: colors[clientList[index].color],
                border: Border.all(width: 2, color: Colors.black),
                borderRadius: BorderRadius.circular(8.0)),
            child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          clientList[index].numerotelephone,
                          style: Theme.of(context).textTheme.bodyText2,
                        ),
                      ),
                    ),
                    Text(
                      getPriorityText(clientList[index].priority),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          clientList[index].code,
                          style: Theme.of(context).textTheme.bodyText2,
                        ),
                      ),
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: Text(clientList[index].prix.toString() ?? 0,
                            style: Theme.of(context).textTheme.bodyText1),
                      )
                    ],
                  ),
                ),
                Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Text(clientList[index].date,
                          style: Theme.of(context).textTheme.subtitle2),
                    ])
              ],
            ),
          ),
        ),
      ),
      staggeredTileBuilder: (int index) => StaggeredTile.fit(axisCount),
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
    );
  }



  void navigateToDetail(Client client, String title) async {
    bool result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) => ClientDetail(client, title)));

    if (result == true) {
      updateListView();
    }
  }

  void updateListView() {
    final Future<Database> dbFuture = databaseHelper.initializeDatabase();
    dbFuture.then((database) {
      Future<List<Client>> clientListFuture = databaseHelper.getClientList();
      clientListFuture.then((clientList) {
        setState(() {
          this.clientList = clientList;
          count = clientList.length;
       
       
        });
      });
    });
  }
}
aiazj4mn

aiazj4mn1#

你可以这样做

List<Map> results = await dbClient.rawQuery(
          "SELECT SUM(col) as TOTAL "
              "FROM MyTable "
              "AND dateTimeStamp >= ? "
              "AND dateTimeStamp <= ? "
              "ORDER BY dateTimeStamp ASC ",
          [fromTimestamp,toTimeStamp]);

相关问题