我在column
中有两个小部件。topLayer
小部件更改了url
。我需要将更改的URL传递给bottomLayer
。如何通过?
class MapBoxExample extends StatefulWidget {
MapBoxExample({Key key}) : super(key: key);
_MapBoxExampleState createState() => _MapBoxExampleState();
}
class _MapBoxExampleState extends State<MapBoxExample> {
@override
Widget build(BuildContext context) {
String url = “”;
return Scaffold(
body: SingleChildScrollView(
child: SafeArea(
child: Column(
children: <Widget>[
topLayer(url),
bottomLayer(url)
]))));}}
Widget topLayer(url){
url = “google.com”
...
}
Widget bottomLayer(url){
…
onPressed:()=> print(url);//Value is null
}
我在WidgetsBinding.instance.addPostFrameCallback((_) => setModelState(() {..}
内尝试过topLayer
。但是这个总是在运行。
是否可以在这里使用simple setState
或bloc
?
答案 0 :(得分:0)
使url为MapBoxExample小部件的变量。并传递一个更改url和setState的函数,以便可以重新构建组件。像这样:
class MapBoxExample extends StatefulWidget {
MapBoxExample({Key key}) : super(key: key);
_MapBoxExampleState createState() => _MapBoxExampleState();
}
class _MapBoxExampleState extends State<MapBoxExample> {
String url = “”;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: SafeArea(
child: Column(
children: <Widget>[
topLayer(updateUrl),
bottomLayer(url)
]))));}}
updateUrl(String updatedUrl) {
setState(() => {
url = updatedUrl;
})
}
Widget topLayer(url){
//run the method updateUrl passing the updateUrl as parameter
}
Widget bottomLayer(url){
…
onPressed:()=> print(url);//Value is null
}