Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: StreamProvider catchError how to

Tags:

stream

flutter

I was wondering if someone could show me how to implement the Flutter StreamProvider "catchError" property?

Example code below to add to:

StreamProvider<LocationModelNormal>.value(
    initialData: LocationModelNormal.initialData(),
    stream: locationStreamInstance.specificLocation(_secondWonder),
    catchError: ?????????
),
class LocationModelNormal {
  final String name;
  LocationModelNormal({
    this.name
  });
  factory LocationModelNormal.fromMap(Map<String, dynamic> data) {
    return LocationModelNormal(
      name: data['name'] ?? '',

    );
  }
  factory LocationModelNormal.initialData() {
    return LocationModelNormal(
      name: '',
    );
  }
}
like image 471
Chris Avatar asked Jul 08 '19 21:07

Chris


1 Answers

You'll want to model your data using sealed classes:

abstract class Data {}

class Content implements Data {
  Content(this.data);

  final List<String> data;
}

class Error implements Data {
  Error(this.msg);

  final String msg;
}

class Loading implements Data {
  const Loading();
}

Then used like so in the provider:

StreamProvider<Data>(
  builder: (_) async* {
    yield Content(['hello', 'world']);
  },
  initialData: const Loading(),
  catchError: (_, err) => Error(err.toString()),
  child: Container(),
);

And consumed as such:

Consumer<Data>(
  builder: (_, data, __) {
    if (data is Loading) {
      return const CircularProgressIndicator();
    } else if (data is Error) {
      return Center(child: Text(data.msg));
    } else if (data is Content) {
      return ListView.builder(
        itemCount: data.data.length,
        itemBuilder: (_, index) => Text(data.data[index]),
      );
    }
    throw FallThroughError();
  },
);
like image 120
Rémi Rousselet Avatar answered Nov 17 '22 15:11

Rémi Rousselet