flutter - 更新外部有状态小部件类的实例时如何更新屏幕
问题描述
我在我的主页上显示一个人类实例的权重。当我通过弹出底部表单中的表单更新此实例的权重时,显示的权重仅在热重载后更改。当主页中的实例参数发生更改时,如何在我的人员类中触发 setState?
main.dart
import 'package:flutter/material.dart';
import 'package:metricwidget/screens/homepage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// Root of application
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Homepage(),
);
}
}
人.dart
import 'package:flutter/material.dart';
class person extends StatefulWidget {
int? weight;
person({Key? key, this.weight}) : super(key: key);
void updateWeight(newWeight){
weight = newWeight;
}
@override
_personState createState() => _personState();
}
class _personState extends State<person> {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
widget.weight.toString(),
style: const TextStyle(fontSize: 24),
),
);
}
}
主页.dart
import 'package:mvs/person.dart';
import 'package:flutter/material.dart';
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
@override
_HomepageState createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
var joe = person(weight: 23);
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Material(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: joe,
),
OutlinedButton(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return Form(
key: _formKey,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: TextFormField(
onSaved: (String? value) {
if (int.parse(value!) > 0) {
setState(() {
joe.updateWeight(int.parse(value));
});
}
},
keyboardType: TextInputType.number,
maxLength: 3,
initialValue: joe.weight.toString(),
decoration: const InputDecoration(
icon: Icon(Icons.label),
),
validator: (value) {
if (value!.isEmpty) {
return "Please enter value";
}
return null;
},
),
),
OutlinedButton(
onPressed: () {
_formKey.currentState!.save();
Navigator.pop(context);
},
child: const Text("submit"),
)
],
),
);
},
);
},
child: const Text("Update"),
)
],
),
);
}
}
解决方案
能够使用提供程序和 changenotifier 解决此问题,与以下文档中概述的格式相同
推荐阅读
- transformation - Dataweave 2 将具有 id 字段的对象数组转换为元素为映射的对象
- amazon-web-services - PowerShell 使用对象锁定将文件复制到 AWS 存储桶
- apache-flink - 使用 flink 间隔连接的状态清理行为
- html - 如何将数据从 HTML 表单发送到 Google Apps 脚本
- google-ai-platform - 自动缩放 VertexAI 管道组件
- python-3.x - 如何在单个位置打印实时数据而不用 python 打印新行?
- excel - 生成第一个宏后无法调用第二个宏
- java - 即使满足所有条件,我的应用程序也不会进入 for 循环
- java - Mockito 测试因 when/thenReturn 失败
- pine-script - 为右轴上的指标添加标签