gpt4 book ai didi

flutter - 如何在子窗口小部件上编辑值

转载 作者:行者123 更新时间:2023-12-03 04:28:04 25 4
gpt4 key购买 nike

我尝试编辑子窗口小部件的值,我可以使用StatefulWidget父级来执行此操作,但我想使用StatelessWidget父级来执行此操作,而无需使用全局值

    class Homepage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
FlatButton(child: Text('addFile'), onPressed: () {}),
FlatButton(child: Text('deleteFile'), onPressed: () {})
],
),
body: Child(),
);
}
}

class Child extends StatefulWidget {
@override
_ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
var hasFile = true;
@override
Widget build(BuildContext context) {
return hasFile ? Text('has a file') : Text("no File");
}
}

最佳答案

您在想错方法。子aka Text()应该从由应用程序管理或至少由上面的小部件管理的模型中获取其值。我将使用提供程序包https://pub.dev/packages/provider并执行以下操作:

import 'package:provider/provider.dart';
import 'package:flutter/material.dart';


class MyState with ChangeNotifier {
String _myText;

MyState(this._myText);

getMyText() => _myText;

void changeText(String newText) {
_myText = newText;
notifyListeners();
}
}

class Homepage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (_) => MyState("initial Text")),
],
child: Scaffold(
appBar: AppBar(
actions: <Widget>[
FlatButton(
child: Text('addFile'),
onPressed: () {
Provider.of<MyState>(context).changeText("addFile");
}),
FlatButton(
child: Text('deleteFile'),
onPressed: () {
Provider.of<MyState>(context).changeText("deleteFile");
})
],
),
body: Child(),
));
}
}

class Child extends StatelessWidget {
@override
Widget build(BuildContext context) {
MyState myState = Provider.of<MyState>(context);
return Text(myState.getMyText());
}
}

这是在没有IDE支持甚至编译和运行的情况下进行编码的。但这应该使您朝正确的方向前进。

关于flutter - 如何在子窗口小部件上编辑值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com