Home > Software design >  is it possible to have type arguments for FutureBuilder in flutter
is it possible to have type arguments for FutureBuilder in flutter

Time:06-23

I'm trying to create a custom future builder for all widgets but when I try to pass Type as an argument its not working anyone knows any way of implementing this

buildFutureBuilder({
  required Widget loadingWidget,
  required Widget errorWidget,
  required Widget child,
  required Future<dynamic> future,
  required Type dynamicType,
}) async {
  return FutureBuilder<dynamicType>(
    future: future,
    builder: (BuildContext context, AsyncSnapshot<dynamicType> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return loadingWidget;
      } else if (snapshot.error == null) {
        return errorWidget;
      } else {
        return child;
      }
    },
  );
}

The error is

The name 'dynamicType' isn't a type so it can't be used as a type argument. Try correcting the name to an existing type, or defining a type named 'dynamicType'

any one knows the correct way to do this

CodePudding user response:

If you want to pass in data of a specific type, you can do it in the following way:

buildFutureBuilder<T>({
    required Widget loadingWidget,
    required Widget errorWidget,
    required Widget child,
    required Future<T> future,
  }) async {
    return FutureBuilder<T>(
      future: future,
      builder: (BuildContext context, AsyncSnapshot<T> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return loadingWidget;
        } else if (snapshot.error == null) {
          return errorWidget;
        } else {
          return child;
        }
      },
    );
  }

You do not need to declare a variable of type Type in order to accept dynamic types of objects. You can do it as above, i.e. Giving the Method a dynamic type T and using that Type T anywhere you would like to use the type.

CodePudding user response:

You should make your buildFutureBuilder generic and pass the type in it:

buildFutureBuilder<Type>({
   required Widget loadingWidget,
   required Widget errorWidget,
   required Widget child,
   required Future<Type> future,
 }) async {
   return FutureBuilder<Type>(
     future: future,
     builder: (BuildContext context, AsyncSnapshot<Type> snapshot) {
     if (snapshot.connectionState == ConnectionState.waiting) {
       return loadingWidget;
     } else if (snapshot.error == null) {
       return errorWidget;
     } else {
       return child;
     }
    },
   );
 }
  • Related