About making searchbar with flutter_riverpod

61 Views Asked by At

I'm new to Flutter. I use the Riverpod state management library. I am calling a remote API to get a list of tv series. If I don't pass a parameter to my query, it returns me a list of popular series, and if I pass a series name parameter, it returns me a list of series containing the parameter in its name. So I want to display a list of popular series when the user lands on the page, and update the list if the user searches for a series by writing its name in the search bar. Thanks.

model ok Data from service is ok provider ok ListView.builder ok I want to add searchbar? Codes...

//Model
class SerieModel {
  final String serieName;
  final String serieImage;

  SerieModel({required this.serieName, required this.serieImage});

  factory SerieModel.fromJson(Map<String, dynamic> json) {
    return SerieModel(serieName: json['serieName'], serieImage: json['serieImage']);
  }
}
//Service
class SerieService {
  SerieService(this.baseUrl);

  String baseUrl;

  Future<List<SerieModel>> getSerie() async {
    Response response = await get(Uri.parse(baseUrl));
    if (response.statusCode == 200) {
      final List result = jsonDecode(response.body)['results'];
      return result.map((e) => SerieModel.fromJson((e))).toList();
    } else {
      throw Exception(response.reasonPhrase);
    }
  }
}
//Provider
final seriesProvider = Provider<SerieService>((ref) => SerieService(seriesUrl));

final seriesDataProvider = FutureProvider<List<SerieModel>>((ref) {
  return ref.read(seriesProvider).getSerie();
});
//HomePage
class HomePage extends ConsumerWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final seriesData = ref.watch(seriesDataProvider);
    return Scaffold(
      appBar: AppBar(),
      body: Column(
      children: [
         const MySearchBar(),//There 
         seriesData.when(
        data: (data) {
          return ListView.builder(
            itemCount: data.length,
            itemBuilder: (context, index) {
              return ListTile(
                leading: Text(data[index].serieName),
                trailing: Icon(Icons.chevron_right, color: Theme.of(context).colorScheme.primary),
              );
            },
          );
        },
        error: ((error, stackTrace) => Text(error.toString())),
        loading: () {
          return const Center(
            child: CircularProgressIndicator(),
            );
          },
        ),
       ],
      ),
    );
  }
}
0

There are 0 best solutions below