android - 在 flutter 中从 initState 调用 scopedModel

我有一个 scopedModel 类,我可以在其中获取数据。问题是我无法使用具有所有 api 请求的范围模型从 InitState 方法呈现这些数据。方法正在被调用,但内部调用没有,所以我的页面初始状态没有正确显示。

void initState() {
    print("Check initState");
    super.initState();
    ScopedModelDescendant<MainModel>(
        builder: (BuildContext context, Widget child, MainModel model) {
      print("Get into the scoped model");
      model.fecthCars();
      model.fecthCities();
      model.fecthBuys(model.getUserDto.token);
      print(model.getBuys().length);
      return;
    });
  }

没有调用任何获取(Api 请求)。 scopedModel 返回一个小部件。我第一次进入经理时需要更新它,就是这样。无需再次调用它。这可能吗?还是应该在我需要的每个文件中硬编码我的 api 请求?

更新

如果您已经设置了作用域模型类,则可以在其中设置这样的 Future

mixin MyModel on Model {
    Future<TypeToReturn> methodName(String param) async {
    Uri uri = new Uri.http('serverUrl', 'api/call');

    return await http.get(uri).then((http.Response response) {
      final List<dynamic> myResponse= json.decode(response.body);

      return myResponse;
    }).catchError((error) {
      print(error);
    });
  }
}

Aftermards 你可以设置你的 FutureBuilder

Widget _buildBody(BuildContext context, MainModel model) {

    return FutureBuilder(
      future:  model.methodName(someString), //This is the method name above
      builder: (context, AsyncSnapshot<TypeToReturn> snapshot) { //type u return
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        } else {
          if (snapshot.data.length == 0)
            return Center(
              child: Text(
                "No Data Found",
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 16.0,
                ),
              ),
            );

          return (create your own widget with the data inside the snapshot)
        }
      },
    );
  }

希望这能更清楚地说明我是如何做到的。

最佳答案

我偶然发现了以下解决方案:

在我的 StatefulWidget 的 State 类中:

@override
void initState() {
  super.initState();
  // and here...
  MyModel model = ScopedModel.of(context);
  // now I can do with the model whatever I need to do:
  Text someVar = model.initialText;
  model.getValuesFromSomewhere();
  // and so on
}

在我看来,这是解决原始问题所述问题的最简单方法。

https://stackoverflow.com/questions/51883755/

相关文章:

dart - 如何使用 flutter 在移动应用程序中禁用多点触控

firebase - 无法为 flutter 构建发布 APK

dart - Flutter:将盒子阴影添加到透明容器

android - 如何使用 Flutter 将图像上传到 Firebase

dart - 回复 : create a dropdown button in flutter

dart - 将类转换为 JSON 或 List

dart - flutter 中的下拉按钮不会将值切换到所选值

flutter - 具有水平、未填充子项的 PageView

dart - 底部带有滚动页脚的 ListView

dart - Flutter Http错误SocketException : OS Error: C