Как я могу рассчитать сумму из базы данных sqflite с помощью цикла for и распечатать его с будущим строителем - PullRequest
0 голосов
/ 10 октября 2019

Я новичок в дартс и трепетании, и я пишу в нем метод for, чтобы добавить данные, полученные из базы данных sqflite, но возвращаемые данные всегда нулевые, пожалуйста, кто-нибудь может мне помочь исправить код;

Объявления и вызов метода в initstate

Future<int> mainTotal;
  int total = 0;
  int multiple;

  @override
  void initState() {
    selectedItems = [];
    super.initState();
    calculateTotal();
  }

Это функция, которая возвращает будущее int

void calculateTotal() async {
    final dao = Provider.of<ItemListDao>(context);
    List<ItemList> itemLists = await dao.getAllItemLists(widget.checkListId);

    for (int i = 0; i < itemLists.length; i++) {
      int noOfItems = itemLists[i].noOfItems as int;
      int unitPrice = itemLists[i].unitPrice as int;
      multiple = noOfItems * unitPrice;
      total += multiple;
    }

    mainTotal = total as Future<int>;
  }

Попытка использовать будущий построитель для получения данных

Center(
          child: FutureBuilder(
            future: mainTotal, // a previously-obtained Future<String> or null
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                case ConnectionState.active:
                case ConnectionState.waiting:
                  return Text('Awaiting result...');
                case ConnectionState.done:
                  if (snapshot.hasError) return Text('Error: ${snapshot.error}');
                  return Text('Total: ${snapshot.data}');
              }
              return null; // unreachable
            },
          ),
        ),

Ответы [ 2 ]

0 голосов
/ 11 октября 2019

Итак, я восстановил свою логику, и это сработало для меня.

Widget _printTotal() {
final dao = Provider.of<ItemListDao>(context);
return FutureBuilder(
  future: dao.getAllItemLists(
      widget.checkListId), // a previously-obtained Future<String> or null
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    List<ItemList> itemList = snapshot.data ?? List();
    switch (snapshot.connectionState) {
      case ConnectionState.none:
      case ConnectionState.active:
      case ConnectionState.waiting:
      // return Center(child: Text('Awaiting result...'));
      case ConnectionState.done:
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        } else {
          return Center(
            child: Text(
              "Total: " + _getTotal(itemList).toString(),
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 25,
                fontWeight: FontWeight.bold,
              ),
            ),
          );
        }
    }
    return null; // unreachable
  },
);
}

И это функция _getTotal

int _getTotal(List<ItemList> itemLists) {
int total = 0;
for (int i = 0; i < itemLists.length; i++) {
  var noOfItems = int.parse(itemLists[i].noOfItems);
  var unitPrice = int.parse(itemLists[i].unitPrice);
  multiple = noOfItems * unitPrice;
  total += multiple;
}
return total;
}
0 голосов
/ 10 октября 2019

В initState () вам нужно вернуть будущее и присвоить его переменной mainTotal, например:

mainTotal = calculateTotal();

В противном случае переменная будет иметь значение null, а когда вы добавите значение позжепеременная, которую FutureBuilder не сможет реализовать.

Вот пример, похожий на ваш код, чтобы понять проблему:

Future<int> mainTotal;
int total = 0;
int multiple;

@override
void initState() {
  super.initState();
  print("before calculateTotal() mainTotal: $mainTotal");
  mainTotal = calculateTotal();
  print("after calculateTotal() mainTotal: $mainTotal");
}

Future<int> calculateTotal() async {
  print("calculateTotal() starting...");
  await Future.delayed(Duration(seconds: 3));
  List<List<int>> itemLists = [
    [1, 2, 3, 4],
    [1, 2, 3, 4],
    [1, 4]
  ];

  for (int i = 0; i < itemLists.length; i++) {
    int noOfItems = itemLists[i].length;
    int unitPrice = itemLists[i].length;
    multiple = noOfItems * unitPrice;
    total += multiple;
  }

  print("calculateTotal() finished");
  return total;
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: FloatingActionButton(
      onPressed: () {
        setState(() {});
      },
    ),
    body: Center(
      child: FutureBuilder(
        future: mainTotal, // a previously-obtained Future<String> or null
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              print("connectionState: none");
              return Text('Awaiting result...');
            case ConnectionState.active:
              print("connectionState: active");
              return Text('Awaiting result...');
            case ConnectionState.waiting:
              print("connectionState: waiting");
              return Text('Awaiting result...');
            case ConnectionState.done:
              print("connectionState: done");
              if (snapshot.hasError) return Text('Error: ${snapshot.error}');
              return Text('Total: ${snapshot.data}');
          }
          return null; // unreachable
        },
      ),
    ),
  );
}

И это вывод отпечатков:

I/flutter (30319): before calculateTotal() mainTotal: null
I/flutter (30319): calculateTotal() starting...
I/flutter (30319): after calculateTotal() mainTotal: Instance of 'Future<int>'
I/flutter (30319): connectionState: waiting
I/flutter (30319): calculateTotal() finished
I/flutter (30319): connectionState: done

Если вы неверните переменную, и вы назначите ее позже, это будет вывод:

I/flutter (30799): before calculateTotal() mainTotal: null
I/flutter (30799): calculateTotal() starting...
I/flutter (30799): after calculateTotal() mainTotal: null
I/flutter (30799): connectionState: none
I/flutter (30799): calculateTotal() finished
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...