如何在构建方法中使用状态管理?

时间:2019-09-30 17:42:00

标签: flutter dart

我在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 setStatebloc

1 个答案:

答案 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
}