【问题标题】:Sum all numbers in a list or alternative way of adding a changing list of variables flutter将列表中的所有数字相加或添加变化的变量列表的替代方式颤动
【发布时间】:2020-12-23 04:36:04
【问题描述】:

您好,我正在尝试构建一个资金管理应用程序。 我在添加列表中的所有数字时遇到问题。

我的想法是我有 2 个按钮(绿色和红色)。用户会添加一个数字,然后点击绿色或红色来显示他们收到的钱或花费的钱。

我无法获取列表的总数或对列表执行数学运算。

我可以使用任何替代方法吗?

import 'package:flutter/material.dart';
import 'package:list_ext/list_ext.dart';

class HomeScreen extends StatefulWidget {
  static final String routeName = "/home";
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  final myController = TextEditingController();
  List<String> in_out = ["One","Two","Three","Four"];
  List<int> amount = [1, 2, 3 ,4];
//  int sum = amount.reduce((a, b) => a + b);
  var money = 0;
  var newMoney = 0;
  var cash = 0;
  var income = 0;
  var spent = 0;


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: buildAppBar(),
      body: buildBody(),
    );
  }


  Widget buildAppBar(){
    return AppBar(
      title: Text('Money Managment App'),
    );
  }

  Widget buildTotal(){
   return Text('$newMoney');// res is 15
  }

  Widget buildBody(){
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              GestureDetector(
                child: Icon(Icons.chevron_left,
                color: Colors.red,
                size: 40,),
                onTap: (){
                  addExpense();
                },
              ),

        Container(
          width: 150,
          child: TextField(
            controller: myController,
            keyboardType: TextInputType.number,
            autocorrect: true,
          ),
        ),

              GestureDetector(
                child: Icon(Icons.chevron_right,
                color: Colors.green,
                size: 40,),
                onTap: () {
                  addIncome();
                },
              ),
            ],
          ),

          buildTotal(),

          SizedBox(height: 20,),

          Container(
            height: 350,
            child: ListView.builder
              (
                itemCount: in_out.length,
                itemBuilder: (BuildContext ctxt, int index) {
                  return Container(
                    height: 30,
                    margin: EdgeInsets.all(2),
                    color: Colors.white,
                    child: Center(
                        child: Text('${in_out[index]} (${amount[index]})',
                          style: TextStyle(fontSize: 18),
                        )
                    ),
                  );
                }
            )
          ),
        ],
      ),
    );
  }

  void total(){
      income = cash + int.parse(myController.text);
      newMoney = money + income;
  }


  void addIncome(){
    setState(() {
      in_out.add('Income',);
      amount.add(int.parse(myController.text));
      total();
    });
  }

  void addExpense(){
    setState(() {
      in_out.add('Expense');
      amount.add(int.parse(myController.text));
    });
  }

  
}

我是 Flutter 的新手。

非常感谢任何关于学习的提示或视频推荐。 提前谢谢你。

【问题讨论】:

    标签: flutter dart banking


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第一步:您可以使用class MoneyList&lt;Money&gt;来记录历史
    第 2 步:您可以将 IncomeExpense 字符串传递给 total 函数,然后进行计算

    代码sn-p

    class Money {
      String in_out;
      int amount;
    
      Money({this.in_out, this.amount});
    }
    
    void total(String in_out) {
        //income = cash + int.parse(myController.text);
        if (in_out == 'Income') {
          newMoney = newMoney + int.parse(myController.text);
        } else {
          newMoney = newMoney - int.parse(myController.text);
        }
      }
    
      void addIncome() {
        setState(() {
          moneyList
              .add(Money(in_out: 'Income', amount: int.parse(myController.text)));
          /* in_out.add('Income',);
          amount.add(int.parse(myController.text));*/
          total('Income');
        });
      }
    
      void addExpense() {
        setState(() {
          moneyList
              .add(Money(in_out: 'Expense', amount: int.parse(myController.text)));
          /*in_out.add('Expense');
          amount.add(int.parse(myController.text));*/
          total('Expense');
        });
      }
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    
    class Money {
      String in_out;
      int amount;
    
      Money({this.in_out, this.amount});
    }
    
    class HomeScreen extends StatefulWidget {
      static final String routeName = "/home";
      @override
      _HomeScreenState createState() => _HomeScreenState();
    }
    
    class _HomeScreenState extends State<HomeScreen> {
      final myController = TextEditingController();
      List<Money> moneyList = [];
      // List<String> in_out = ["One","Two","Three","Four"];
      //List<int> amount = [1, 2, 3 ,4];
    //  int sum = amount.reduce((a, b) => a + b);
      var money = 0;
      var newMoney = 0;
      var cash = 0;
      var income = 0;
      var spent = 0;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: buildAppBar(),
          body: buildBody(),
        );
      }
    
      Widget buildAppBar() {
        return AppBar(
          title: Text('Money Managment App'),
        );
      }
    
      Widget buildTotal() {
        return Text('$newMoney'); // res is 15
      }
    
      Widget buildBody() {
        return Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    child: Icon(
                      Icons.chevron_left,
                      color: Colors.red,
                      size: 40,
                    ),
                    onTap: () {
                      addExpense();
                    },
                  ),
                  Container(
                    width: 150,
                    child: TextField(
                      controller: myController,
                      keyboardType: TextInputType.number,
                      autocorrect: true,
                    ),
                  ),
                  GestureDetector(
                    child: Icon(
                      Icons.chevron_right,
                      color: Colors.green,
                      size: 40,
                    ),
                    onTap: () {
                      addIncome();
                    },
                  ),
                ],
              ),
              buildTotal(),
              SizedBox(
                height: 20,
              ),
              Container(
                  height: 350,
                  child: ListView.builder(
                      itemCount: moneyList.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return Container(
                          height: 30,
                          margin: EdgeInsets.all(2),
                          color: Colors.white,
                          child: Center(
                              child: Text(
                            '${moneyList[index].in_out} (${moneyList[index].amount})',
                            style: TextStyle(fontSize: 18),
                          )),
                        );
                      })),
            ],
          ),
        );
      }
    
      void total(String in_out) {
        //income = cash + int.parse(myController.text);
        if (in_out == 'Income') {
          newMoney = newMoney + int.parse(myController.text);
        } else {
          newMoney = newMoney - int.parse(myController.text);
        }
      }
    
      void addIncome() {
        setState(() {
          moneyList
              .add(Money(in_out: 'Income', amount: int.parse(myController.text)));
          /* in_out.add('Income',);
          amount.add(int.parse(myController.text));*/
          total('Income');
        });
      }
    
      void addExpense() {
        setState(() {
          moneyList
              .add(Money(in_out: 'Expense', amount: int.parse(myController.text)));
          /*in_out.add('Expense');
          amount.add(int.parse(myController.text));*/
          total('Expense');
        });
      }
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: HomeScreen(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    【讨论】:

    • 很高兴为您提供帮助。如果对您有帮助,请将其标记为答案。谢谢
    猜你喜欢
    • 2021-12-27
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多