I am totally new to Flutter/Dart
and I am designing an app so I can practice. I am facing an error that I didn´t find here, neither ChatGPT
could give me a proper solution.
Please, what´s going on?
main.dart
import 'package:bloc_pattern/bloc_pattern.dart';
import 'package:flutter/material.dart';
import 'package:you_flu/blocs/videos_bloc.dart';
import 'package:you_flu/screens/home.dart';
void main() => runApp(const YouFlu());
class YouFlu extends StatelessWidget {
const YouFlu({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
blocs: [VideosBloc()], //Error here
dependencies: const [],
child: const MaterialApp(
debugShowCheckedModeBanner: false,
title: 'YouFlu',
home: Home(),
),
);
}
}
The error states that here: blocs: [VideosBloc()],
The element type 'VideosBloc' can't be assigned to the list type 'Bloc<dynamic>'.dartlist_element_type_not_assignable
I already tried:
blocs: VideosBloc(),
so with, and without the brackets.
Here is my VideosBloc class
import 'dart:ui';
import 'package:bloc_pattern/bloc_pattern.dart';
import 'package:you_flu/api.dart';
import 'dart:async';
import 'package:you_flu/models/video.dart';
class VideosBloc implements BlocBase {
late Api api;
late List<Video> videos;
final StreamController _videosController = StreamController();
Stream get outVideos => _videosController.stream;
final StreamController _searchController = StreamController();
Sink get inSearch => _searchController.sink;
VideosBloc() {
api = Api();
_searchController.stream.listen(_search as void Function(dynamic event)?);
}
void _search(String search) async {
videos = await api.search(search);
}
@override
void dispose() {
_videosController.close();
_searchController.close();
}
@override
void addListener(VoidCallback listener) {}
@override
bool get hasListeners => throw UnimplementedError();
@override
void notifyListeners() {}
@override
void removeListener(VoidCallback listener) {}
}
ChatGPT
told me that the implementation of the VideosBloc
class looks good.
Oh, before I forget: Here is my pubspec.yaml
so you guys can check the versions I´m using:
name: you_flu
description: "Youtube Flutter"
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.3.4 <4.0.0'
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
youtube_player_flutter: ^9.0.1
http: ^1.2.1
shared_preferences: ^2.2.3
rxdart: ^0.27.7
bloc_pattern: ^3.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
assets:
- images/
Well so, why can´t I assign my VideosBloc
class to the blocs
property on BlocProvider
?
Thanks!
Well... I found the answer, and it was very very simple:
return BlocProvider(
blocs: [
Bloc((i) => VideosBloc())
],
// other stuff...
),
);
Create a list using the brackets, and then use a function
from the Bloc
class to assign my VideosBloc
class to a Bloc
.