gpt4 book ai didi

flutter - 当按下按钮时 flutter 更新第二个父级

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

我正在使用Flutter应用程序,并且想在按下按钮时更新第二级父级的状态。当按下“PressMe”按钮时,我希望MyHomePage的状态以其自身状态保存Widget2的标题字符串。有人可以帮我这个忙吗?该按钮是一个较低级别的小部件,我想将数据向上传递两个级别。谢谢!

//main.dart
import 'package:flutter/material.dart';
import 'Widget1.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(

primarySwatch: Colors.blue,
),

home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
String title2;
@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text("Hello"),
),
body: Center(
child: Widget1(),
),
);
}
}
///////////////////////////////
//Widget1.dart
import 'package:flutter/material.dart';
import 'Widget2.dart';


class Widget1 extends StatefulWidget {
_Widget1State createState() => _Widget1State();
}

class _Widget1State extends State<Widget1> {

@override
Widget build(BuildContext context) {
return Widget2();
}
}
///////////////////////////////
//Widget2.dart

import 'package:flutter/material.dart';

class Widget2 extends StatefulWidget {

final String title = "Hello from Widget2";


_Widget2State createState() => _Widget2State();
}

class _Widget2State extends State<Widget2> {
String title = "Hello from Widget2";


@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: null,
child: Text(
'PressMe',
style: TextStyle(fontSize: 20)
),
);
}
}


谢谢!

最佳答案

从子级更新父级窗口小部件/类的最简单方法是传递在父级中创建的function,然后在需要更新子级时从子级调用该函数。但是,如果您需要将其传递给多个子对象,那就太麻烦了。通常,在这种情况下,您希望您的 parent 是StatefulWidget,并在分配新标题时在创建的函数内调用setState

下一个解决方案是使用InheritedWidgetChangeNotifier

理想的解决方案是使用某种形式的状态管理,例如ProviderBloc

关于flutter - 当按下按钮时 flutter 更新第二个父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831368/

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