如何从回叫中获取小部件?

时间:2020-09-03 17:50:20

标签: flutter

class AsyncBuilder<T> extends FutureBuilder<Result> {
  Widget loading = Center(child: CircularProgressIndicator());
  Widget onError = Center(
    child: Text("loading failed, Please reload again"),
  );
  final Callback callback;
  final Future<Result<T>> f;


  AsyncBuilder(this.f, this.onSuccess, {this.loading, this.onError})
      : super(
            future: f,
            initialData: Result(Result.RESULT_LOADING, null, null),
            builder: (context, snapshot) {
              Widget w = loading;
              if (snapshot.hasError) {
                w = onError;
              } else if (snapshot.hasData) {
                if (snapshot.data.status == Status.LOADING) {
                  w = loading;
                } else if (snapshot.data.status == Status.SUCCESS) {
                  w = callback.call(snapshot.data);
                } else if (snapshot.data.status == Status.UNAUTHENTICATED) {
                  w = MyLogin();
                }
              }
              return w;
            });
}

如上面的代码,我想从widget获得一个callback.call(snapshot)并将snapshot.data传递给该call方法。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

最后解决此问题。 代码如下。

typedef Widget SuccessCallback<T>(T data);

class AsyncBuilder<T> extends FutureBuilder<Result> {
  Widget loading ;
  Widget onError ;
  final Future<Result<T>> f;
  final SuccessCallback<T> callback;


  AsyncBuilder(this.f, this.callback, {this.loading, this.onError})
      : super(
            future: f,
            initialData: Result(Result.RESULT_LOADING, null, null),
            builder: (context, snapshot) {

              Widget w;
              if (snapshot.hasError) {
                if(onError == null){
                  w = Center(
                    child: Text("loading failed, Please reload again"),
                  );
                }else{
                  w = onError;
                }

              } else if (snapshot.hasData) {
                if (snapshot.data.status == Status.LOADING) {
                  if(loading == null){
                    w =  Center(child: CircularProgressIndicator());
                  }else{
                    w= loading;
                  }
                } else if (snapshot.data.status == Status.SUCCESS) {
                  w = callback.call(snapshot.data.data);
                } else if (snapshot.data.status == Status.UNAUTHENTICATED) {
                  w = MyLogin();
                }
              }
              return w;
            });
}