如何使用浮动操作按钮更新自定义状态小部件

时间:2020-03-17 16:01:35

标签: flutter

我最近刚开始使用Flutter只是为了好玩,而我一直坚持将实际功能添加到代码中,而没有将所有内容都放在一个类中。

基本上,我正在尝试使用FloatingActionButton来增加Text小部件的值,该小部件将用户级别的值存储为整数,但是我不想将整个应用程序设为StatefulWidget,因为将仅更新级别。按下按钮时,该值应增加1,然后在屏幕上显示新值。

我在Text类中具有“级别StatefulWidget”小部件以及一个将级别更新1并设置状态的函数; MaterialApp类中的StatelessWidget;以及另一个StatelessWidget类中的主体代码。

如果这不是最好的方法,请告诉我,以便为以后的项目进行改进,谢谢。

main.dart

import 'package:flutter/material.dart';

main() => runApp(Start());

/// The Material App
class Start extends StatelessWidget{ 
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.grey[800],

        appBar: AppBar(
          title: Text("Home Page"),
          backgroundColor: Colors.cyan,
          centerTitle: true,
        ),

        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          backgroundColor: Colors.orange,
          child: Icon(Icons.add, color: Colors.black,),
        ),

        body: HomePage(),
      ),
    );
  }
}

/// Main Content for the page (body)
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,

        children: <Widget>[

          // removed other children so there's less code to scan through for you :)

          Padding(
            padding: EdgeInsets.fromLTRB(30, 0, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[

                // Text that just says "Level"
                Text(
                  "Level",
                  style: TextStyle(
                    color: Colors.orange,
                    fontWeight: FontWeight.bold,
                    fontSize: 32,
                  ),
                ),

                // space between text and actual level value
                SizedBox(height: 10),

                // Create new level widget
                Level(),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// Updating level using a Stateful Widget
class Level extends StatefulWidget{
  @override
  State<StatefulWidget> createState(){
    return _LevelState();
  }
}

class _LevelState extends State<Level>{
  int level = 0;

  void incrementLevel(){
    setState(() {
      level += 1;
    });
  }

  @override
  Widget build(BuildContext context){
    return Text(
      "$level",
      style: TextStyle(
        color: Colors.grey[900],
        fontWeight: FontWeight.normal,
        fontSize: 28,
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

这实际上是一种奇怪的方法。但是,有多种方法可以实现这一目标

举个例子:

您可以使用KEY远程重绘子状态

如果您需要可以在大型项目中为您提供帮助的高级解决方案。您可以使用状态管理技术。您可以在互联网上找到很多教程,但这只是其中一些。 BLOC,提供程序,InheritedWidget。

基本上,他们都做同样的事情。提起状态数据,因此重新绘制的窗口小部件在窗口小部件树上的位置将不重要。

我强烈建议您观看一些有关提供商的教程。希望对您有帮助