flutter - 如何使用浮动操作按钮更新自定义有状态小部件
问题描述
我最近开始使用 Flutter 只是为了好玩,我一直坚持在代码中添加实际功能,而不是把所有东西都放在一个类中。
本质上,我试图使用 aFloatingActionButton
来增加Text
Widget 的值,它将用户级别的值存储为整数,但我不想将整个应用程序作为 a StatefulWidget
,因为只有级别会被更新. 按下按钮时,值应增加 1,然后在屏幕上显示新值。
我Text
在一个StatefulWidget
类中有一个级别小部件以及一个将级别更新为一级并设置状态的函数;类MaterialApp
里面StatelessWidget
;StatelessWidget
以及另一个类中的主体代码。
如果这不是最好的方法,请告诉我,以便我可以改进未来的项目,谢谢。
主要.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,
),
);
}
}
解决方案
这实际上是一种奇怪的做法。但是,有多种方法可以实现这一目标
举个例子:
您可以使用 KEY 远程重绘子状态
如果您想要一个可以帮助您完成更大项目的高级解决方案。您可以使用状态管理技术。你可以在互联网上找到很多教程,但这些只是其中的一部分。BLOC,提供者,InheritedWidget。
基本上他们都做同样的事情。提升状态数据,因此重绘的小部件在小部件树上的位置将不重要。
我强烈建议您从 Provider 开始观看一些教程。我希望这有帮助
推荐阅读
- java - 客户端-服务器应用程序的 JPA 悲观锁逻辑
- javascript - 从按钮更改为页面加载弹出窗口
- angular - 当项目不为空时显示箭头
- javascript - 如何在不丢失输入数据的情况下更新 url
- r - 使用 r 中的 rnorm 函数为变量赋值
- python - 在大文本文件 python 上查找
- pandas - 使用 groupby() 从后面进行累积乘法
- python - 为什么以不同的方式生成数组会导致代码不同部分的大量加速?
- javascript - ES8 和 ES9 中的 jshint 指的是什么?
- r - 错误 1:从 JavaScript 动态生成 Web 抓取时下标越界