如何在Flutter中显示工具栏操作的批次计数?

时间:2019-07-15 03:00:08

标签: flutter toolbar

我正在使用购物车类型的应用程序,需要在其中显示购物车项目计数。如何在工具栏操作中显示项目计数。我冲浪很多找不到解决方法。

1 个答案:

答案 0 :(得分:0)

您只需在Action小部件中添加带有图片和文字的按钮即可,AppBar。然后,无论何时添加项目,都需要更新操作中的文本。这里是一个简单的示例:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    title: "Sample",
    home: new Home(),
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  // save the total of the item here.
  int _total = 0;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(

      // add the AppBar to the page
      appBar: new AppBar(
        actions: <Widget>[

          // Add a FlatButton as an Action for the AppBar
          FlatButton(
            onPressed: () => {},
            child: Row(
              children: <Widget>[
                Icon(Icons.shop),
                Text("Total $_total")
              ],
            ),
          )
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _increaseTotal,
        tooltip: "Add",
      ),
    );
  }

  // increase the total item whenever you click the FloatingActionBar
  void _increaseTotal() {
    setState(() {
      _total++;
    });
  }
}