dart flutter error -期望值为“String”类型,但得到的值为“int”类型

lhcgjxsq  于 2023-06-27  发布在  Flutter
关注(0)|答案(2)|浏览(131)

这是我在Flutter应用程序中的函数,通过将列表中的产品价格和产品数量相乘来计算产品的最终价格

int calci() {
  int totalPrice = 0;
  for (int i = 0; i < cartitem.length; i++) {
    int price = int.parse(cartitem[i][1]);
    int quantity = int.parse(cartitem[i][4]);
    totalPrice += price * quantity;
  }
  return totalPrice;
}

这是我显示它的代码

Text(
  '₹${calci().toString()}',
  style: const TextStyle(
    fontSize: 18,
    fontWeight: FontWeight.bold,
    color: Colors.white,
  ),
),

现在运行应用程序后,这给了我一个类型转换的错误,我不知道我试了很多,但无法解决它。
Expected a value of type 'String', but got one of type 'int'

cgh8pdjw

cgh8pdjw1#

确保你的cartitem List没有动态类型的元素,比如:

List cartitem = [
  ["Apple", 100, 1, 100, 1],
  ["Banana", "50", "1", "50", "1"],
];

List cartitem = [
  ["Grapes", "120", "1", 120, 4 ],
  ["Mango", "150", "1", 150,  4 ],
];

将cartitem声明为:

List<String> cartitem = {
  ["Banana", "50", "1", "50", "1"],
];

尽管我建议使用item类型的对象列表,例如:
示例:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    List cartitem = [
      Item(name: "Apple", price: 100, quantity: 1),
      Item(name: "Banana", price: 50, quantity: 1),
      Item(name: "Orange", price: 80, quantity: 1),
      Item(name: "Grapes", price: 120, quantity: 1),
    ];

    num calci() {
      num totalPrice = 0;
      for (var item in cartitem) {
        totalPrice += item.price * item.quantity;
      }
      return totalPrice;
    }

    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(
            '₹${calci().toString()}',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
        ),
      ),
    );
  }
}

class Item {
  Item({required this.name, required this.price, required this.quantity});
  final String name;
  final double price;
  final int quantity;
}
piok6c0g

piok6c0g2#

Int.parse需要解析一个字符串。购物车项目可能是一个整数。你可以试试

int.parse(cartitem[i][1].toString())

相关问题