首页 > 解决方案 > 如何使用浮动操作按钮更新自定义有状态小部件

问题描述

我最近开始使用 Flutter 只是为了好玩,我一直坚持在代码中添加实际功能,而不是把所有东西都放在一个类中。

本质上,我试图使用 aFloatingActionButton来增加TextWidget 的值,它将用户级别的值存储为整数,但我不想将整个应用程序作为 a StatefulWidget,因为只有级别会被更新. 按下按钮时,值应增加 1,然后在屏幕上显示新值。

Text在一个StatefulWidget类中有一个级别小部件以及一个将级别更新为一级并设置状态的函数;类MaterialApp里面StatelessWidgetStatelessWidget以及另一个类中的主体代码。

如果这不是最好的方法,请告诉我,以便我可以改进未来的项目,谢谢。

主要.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,
      ),
    );
  }
}

标签: flutter

解决方案


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

举个例子:

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

如果您想要一个可以帮助您完成更大项目的高级解决方案。您可以使用状态管理技术。你可以在互联网上找到很多教程,但这些只是其中的一部分。BLOC,提供者,InheritedWidget。

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

我强烈建议您从 Provider 开始观看一些教程。我希望这有帮助


推荐阅读