Flutter BLoC Library Tutorial - Simple BLoC Pattern Solution

Поділитися
Вставка
  • Опубліковано 21 лип 2024
  • 📗 Get the code from this tutorial 👇👇
    resocoder.com/flutter-bloc-li...
    👨‍💻 Do you write good code? Find out now 👇
    resocoder.com/good-code-quiz
    Flutter BLoC Library: pub.dartlang.org/packages/flu...
    Having a structured codebase can only help you with creating good, long-lasting apps. The problem is that proper architecture can come with a cost of writing a lot of boilerplate code, especially if you intend to write everything from scratch.
    When it comes to the BLoC pattern for Flutter, in the previous tutorial you could see how to create BLoCs from scratch and I'd say it's not something you want to be doing over and over again. It's just too low level. Also, if you don't know how to implement BLoCs from scratch, definitely check it out.
    We need to move up the abstraction ladder so that we aren't going to be dealing with Streams and Sinks directly. This can be done with a handy library about which you are going to learn in this tutorial.
    Go to my website for more information, code examples and articles:
    ● resocoder.com
    Follow me on social media:
    ● / resocoder
    ● / resocoder
    ● / resocoder
    ● gab.ai/resocoder
    Book icon designed by Becris (www.flaticon.com/authors/becris), licensed by creativecommons.org/licenses/b...

КОМЕНТАРІ • 89

  • @ResoCoder
    @ResoCoder  4 роки тому +5

    🚨 Check out the tutorial covering the newest version of the Bloc package:
    ua-cam.com/video/y564ETOCog8/v-deo.html

    • @monikasharma3403
      @monikasharma3403 2 роки тому

      hi Reso Coder, nice tutorial, but i. have some doubt when i create CounterState._() its gives me an error Non-nullable instance field 'counter' must be initialized. I am using bloc library. with version 7.0.0. please help me with this.

  • @AbdulmalikHamid
    @AbdulmalikHamid 5 років тому +24

    This is the best bloc tutorial EVER!

  • @sephyshen2510
    @sephyshen2510 5 років тому

    Very helpful. Thanks for the video. Looking forward to your next tutorial.

  • @JmGodlike
    @JmGodlike 5 років тому +16

    Thanks for the video. Was really helpful!
    Would be grateful if you can maybe do an end-to-end complex app implementation of the BLoC library, with repository call to API call and local db retrieval. The doc skipped those part for simplicity. Looking forward to that, thanks again!

    • @aislanarislou
      @aislanarislou 5 років тому +1

      Local db is something I'm looking for as well.

  • @user-rz6zn5uc7e
    @user-rz6zn5uc7e 5 років тому

    Really great bloc tutorial.

  • @38sabbath38
    @38sabbath38 4 роки тому

    Thanks a lot! Great tutorial

  • @franz5944
    @franz5944 5 років тому

    Really helpful. Thank you.

  • @ibraheemdev2290
    @ibraheemdev2290 5 років тому

    Great and helpful tutorial, thanks

  • @SakshatShinde
    @SakshatShinde 5 років тому +8

    Would you be making a complete flutter tutorial from the beginner level to advanced? Your teaching style is great!

    • @ResoCoder
      @ResoCoder  5 років тому +5

      Yes, although currently I have only an intermediate tutorial planned.

    • @SakshatShinde
      @SakshatShinde 5 років тому +1

      @@ResoCoder Sure, maybe in future I guess!
      Great work though!

  • @theolm
    @theolm 5 років тому +2

    Great tutorial.
    Please make a full app in flutter, like the weather app. =D

  • @filipsavic2165
    @filipsavic2165 4 роки тому +4

    For anyone doing this at flutter_bloc version 4.0.0, the counter_bloc.dart mapEventToState() method should look like this:
    @override
    Stream mapEventToState(CounterEvent event) async* {
    if (event is IncrementEvent) {
    yield state..counter += 1;
    } else if (event is DecrementEvent) {
    yield state..counter -= 1;
    }
    }
    (No need to pass 'CounterState currentState' to the function.)

  • @oztech
    @oztech 5 років тому +4

    This BLOC tutorial is the best i've seen so far in UA-cam! however, async* and yield was never seen before and still not understanding.

    • @codeityourself8064
      @codeityourself8064 3 роки тому

      Maybe this is a late answer, but when you use the yield function, for a better understanding, it will return a list. By example, if you use yield inside a for loop of 100 iterations, it will return a list of 100 items, and in Flutter, async* is linked to it (as long as I know)

  • @ResoCoder
    @ResoCoder  5 років тому +9

    If you want to follow this tutorial, either use the library version 0.4.12 or read on! *Check out the replies for a solution*
    There is one breaking change in 0.5.0 and onwards. Duplicate states are no longer emitted by the bloc. If you want to use the new version, you have to override the == operator, and also not edit currentState directly when incrementing, but rather make a copy of the object. In other words, make CounterState an immutable class.
    If you know how to do this, cool. If not, just use the older version and wait for another tutorial where we will use the built_value library which can create data classes which are immutable and nice to work with.

    • @gmc254quads6
      @gmc254quads6 5 років тому

      Thanks. I should have read this before trying it out. I was almost going nuts trying to do a similar thing to the point I cloned your app from Github and it worked. Then I changed the bloc version and it broke down leading me to the comments. Looking forward to your next tutorial on this.

    • @ilirvasili8847
      @ilirvasili8847 5 років тому +3

      Simple changes I made for it to work with the latest bloc:
      1.
      factory CounterState.initial(int times) {
      return CounterState._()..counter = times;
      }
      2.
      CounterState get initialState => CounterState.initial(0);
      3.
      on mapEventToState() replace
      yield currentState..counter += 1;
      yield currentState..counter -= 1;
      respectively with
      yield CounterState.initial(currentState.counter + 1);
      yield CounterState.initial(currentState.counter - 1);
      Thanks

    • @chinyun1526
      @chinyun1526 5 років тому

      Yeah, I think this video is not that helpful, now. I learned from this and stuck for hours because the view not update with same state (same instance). You should make your comment stick on top to prevent someone stucking.

  • @wexywexywex
    @wexywexywex 3 роки тому +2

    Hello. I just followed this tutorial and things seems to be totally out of sync with bloc_provider now. did the updates to bloc_provider really change how code is written in the last few years? if so have you made a new video showing how to use bloc_providers more recent api?

  • @zehijean8817
    @zehijean8817 5 років тому

    Great explaining...would you mind showing a more elaborate exemple with two blocks communicating together alongside with dealing with resources fetched from the network(DB,API) great stuff

  • @walidbagh
    @walidbagh 5 років тому

    Nice follow-up :D

  • @user-fh4xo2pc2d
    @user-fh4xo2pc2d 5 років тому

    Awesome! How about an example app with basic auth + other features. Thank you!

  • @michalrv3066
    @michalrv3066 5 років тому

    Any reason why you used Classes for events instead of Enums like shown in docs? Anyways, I'm wondering what would be the best way of passing data to bloc, like product ID received from previous screen so it can go ahead and fetch the necessary data :/

  • @MattDuarte11
    @MattDuarte11 5 років тому

    This is like redux for React. Only with classes. Also I am new to Flutter just started. Is there a way to connect my app to a DB? Like PostgreSQL or mongo? Basically where does the backend come in?

  • @MrLarryQ
    @MrLarryQ 5 років тому

    Your tutorials are fantastic, however I think this one went a bit too quick toward the end, particularly the BlocProvider.of stuff. I know what you're doing but that's because I've used Blocs before. Someone new to them, and to the flutter_bloc library, who hasn't seen it before would probably be confused by the last 5-7 minutes. May I suggest a separate video that goes a bit more detail into how to use the flutter_bloc library and all the BlocProvider.of code?

  • @MarciMatuz
    @MarciMatuz 5 років тому +2

    I love BLOC pattern but this package is like ScopedModel package.
    Basicly if your state object has multiple properties and if you use multiple BlocBuilder with same bloc instance and whenever you dispatch an event then all BlocBuilders builder method rerun even if some of them not intrested in the changed property. So better use StreamBuilder with Streams instead of you get the whole state as parameter in build method.

  • @guybashan9897
    @guybashan9897 5 років тому

    Thanks for the GREAT video. Not sure I quite understand the last part with the BlocProvider. For example, if I have method creating some Widget, I will have to pass to it as a parameter the context (in order to use the BlocProvider). So what is the difference between passing the context or the BLOC as a parameter?

    • @ResoCoder
      @ResoCoder  5 років тому

      I'm glad you liked the video, Guy! The difference is that you can get the Bloc from the provider even down the widget tree (from a different class).
      Let's say you have a HomePage widget which contains a UserListView widget to keep the code clean. With BlocProvider, you can easily access the Bloc instantiated in the HomePage inside the UserListView.
      I hope this makes sense, check out some of my newer Bloc tutorials. Things have changed a bit since this video was published.

  • @govingupta5065
    @govingupta5065 5 років тому

    Please explain in detail about bloc builder ,bloc provider, bloc listner in which case what we should use this all ...BTW great tuts..

  • @NelZFS
    @NelZFS 5 років тому

    very good!

  • @SAlmanKhanDev
    @SAlmanKhanDev 5 років тому

    Hey, thanks for the nice tutorial. I request you to create one video covering redux! Thanks again!

  • @furkanvatandas4819
    @furkanvatandas4819 5 років тому

    Awesomee thanks

  • @creative-commons-videos
    @creative-commons-videos 5 років тому

    Validation please, i am not able to integrate validation part for flutter_bloc library

  •  5 років тому

    What you need multiple blocs? Let's say you need one bloc to manage all the states and another one for managing a database logic, or the state of a user authentication? thanks

    •  5 років тому

      I think I found my answer, I see there is a BlocDelegate on the library which basically "is a singleton which oversees all Blocs and delegates responsibilities to the BlocDelegate." Is that how you would solve it? I don't like the usage of Singleton.

  • @LuisOtavio-dt8nu
    @LuisOtavio-dt8nu 4 роки тому

    Nice Tutorial, but i had a problem when i ran it: "Error: No named parameter with the name 'seedValue'. "
    I fixed it by replacing the version flutter_bloc: ^0.4.12 to flutter_bloc: ^0.8.0 .

  • @latifamuhammadi7663
    @latifamuhammadi7663 4 роки тому

    You are awesome sir
    Please do more videos on real app using apis with Bloc

  • @nishantdesai3705
    @nishantdesai3705 5 років тому +2

    Hi, how can we use flutter_bloc when a widget depends on more than one blocs ?
    for example I have a widget w1 which depends on data from remote server (bloc1) and a bloc which responds to internet connectivity (bloc2), as all pages (including the one which has widget w1) of my app responds to change in internet connectivity I decided to use bloc for that too, now how can I use both of these blocs (viz bloc1 and bloc2) to render widget w1 ? Do i have to use nested bloc providers ? or is there a better way ?

    • @aislanarislou
      @aislanarislou 5 років тому

      For what I've seen in another tutorial from documentation, you can use nested blocs.

  • @mysandyballs
    @mysandyballs 5 років тому +5

    The approach of using a counter variable within a CounterState class in any flutter_bloc release above 0.4.12 (I tested with 0.5.4) will no longer work in this example, as it mutates state rather than returning a new state. To fix, I needed to change CounterBloc declaration to:
    class CounterBloc extends Bloc
    (I tried to raise an issue on your GitHub page, but Issue Submit is disabled).

    • @Felangelov
      @Felangelov 5 років тому +5

      The repo is now updated to work with the latest version of flutter_bloc

  • @stijnmathysen7453
    @stijnmathysen7453 5 років тому +1

    Another great tutorial!
    Just a thought; to clean up your onPressed: anonymous functions, you could change;
    onPressed: () => BlocProvider.of(context).onIncrement(),
    to
    onPressed: BlocProvider.of(context).onIncrement,
    Also, while following allong I found it better to stick with flutter_bloc: ^0.4.12 instead of the latest version ^0.5.0 which was recently released. I just can't seem to get it to work with the latest version?

    • @ResoCoder
      @ResoCoder  5 років тому

      Oh, I hope there are no breaking changes in 0.5.0!

    • @ResoCoder
      @ResoCoder  5 років тому +1

      Actually, I found out that there is one breaking change. Duplicate states are no longer emitted by the bloc. If you want to use the new version, you have to override == operator, and also not edit currentState directly when incrementing, but rather make a copy of the object. In other words, make CounterState an immutable class.

  • @miabellasalonandmedicalspa2822
    @miabellasalonandmedicalspa2822 5 років тому +1

    sounds like redux renamed so code grows fast?

  • @leukongsun4845
    @leukongsun4845 5 років тому

    What is cascading operator?

  • @mostasimbillah
    @mostasimbillah 5 років тому

    when you will be publish android mvvm tutorial next part?

  • @simonekang2475
    @simonekang2475 4 роки тому

    why i got a error when I put CounterEvent parameter on mapEventToState. there is error on @override, it says "'CounterBloc.mapEventToState' ('Stream Function(CounterState, CounterEvent)') isn't a valid override of 'Bloc.mapEventToState' ('Stream Function(CounterEvent)').dart(invalid_override)"

  • @TheVikke2
    @TheVikke2 5 років тому

    Hey, I had a weird bug/glitch where BlocBuilder did not update the screen. I thought I had made a mistake in the code, but everything was as in the example. Took me hours to work it out but after I reran *flutter packages get* it started to work. Was weird because the bloc worked and I got print statements but the screen didn't change. Any idea what caused this?

    • @ResoCoder
      @ResoCoder  5 років тому

      No idea, I'm glad you got it solved.

  • @sadekhossain9566
    @sadekhossain9566 5 років тому

    Hi, i am curious how you will use/call a different bloc lets say updateUserBloc that doesn't exists in counter bloc and you want to use properties from both bloc in the the same widget? How you will use from two or more different blocs?

    • @ResoCoder
      @ResoCoder  5 років тому +1

      In addition to BlocProvider there is also a BlocProviderTree which lets you specify a list of Blocs.

    • @sadekhossain9566
      @sadekhossain9566 5 років тому

      Is there any documentation page for all these? Many thanks

    • @ResoCoder
      @ResoCoder  5 років тому +1

      Of course! felangel.github.io/bloc/#/

  • @Daaab89
    @Daaab89 5 років тому +1

    very good tutorial. Short yet straight to the point.
    I've got one question: What if you want your bloc only to listen to database changes (or for example Firestore data changes), and you only need stream with no sink (no events passed - you only listen to data ) - is it possible with this library ?
    Also I'm a little bit confused about mapEventToState. First of all you have to map Event not to State but to Stream (of States). And the second thing is (please correct me if Im wrong) that I thought that you should subscribe to the stream of States, and emit new state when it changes, yet here you have to return new Stream each time State changes - I dont see any difference between returning Stream of States each time State changes, and returning State itself.

    • @ThinkDigitalRepair
      @ThinkDigitalRepair 5 років тому

      The library doesn't stop you from doing anything. So yes, any questions you ask about if it's possible, the answer is yes. It's just a pattern. What you can do is add a listener to the API and onData, bloc.dispatch(myApiEvent()) and set that off on the side somewhere in a function that you call on an initState.

  • @tribeworld5360
    @tribeworld5360 3 роки тому

    Why does the constructor have ._() ? and why does the factory constructor return ._()..counter

  • @hemlock7564
    @hemlock7564 3 роки тому

    Bro I'm a beginner at this flutter thing am an android dev can you please upload beginner level tutorials it'll be very helpful ❤️

  • @semih3043
    @semih3043 3 роки тому

    BLoC makes me
    🤯

  • @vrushangdesai2813
    @vrushangdesai2813 4 роки тому

    Bro pls add one video using multibloc

  • @anirudhamahale8715
    @anirudhamahale8715 5 років тому +1

    I did exactly what you did still my UI didn't update. Then I just copied your class ContainerWidget and it worked😂 But anyways the tutorial was 🔥

    • @arifikhsanudin9724
      @arifikhsanudin9724 5 років тому

      same with me. just writing the same code doesnt work. but after copied, everything just fine

  • @sajad2126
    @sajad2126 4 роки тому

    now it is on version flutter_bloc: ^4.0.0 please make new video with new version . thank you

  • @piyushdongre325
    @piyushdongre325 4 роки тому

    Watch previous video in the series to get your concepts clear

  • @chrisik100
    @chrisik100 4 роки тому +1

    Sooo fu*king hard!

  • @jacintoJoao
    @jacintoJoao 4 роки тому +1

    this is for any dummy person like me> the new version
    flutter_bloc: ^0.21.0 above
    Make changes for the following lines:
    return BlocProvider(
    builder: _counterBloc,
    child: CounterWidget(),
    );
    to
    return BlocProvider(
    builder: (BuildContext context) => CounterBloc(),
    child: CounterWidget(),
    );

  • @simonhutton2497
    @simonhutton2497 4 роки тому

    Unfortunately this tutorial is out of date and shouldn't really be here any more. The updated tutorial (referenced in the pinned comment above) uses a totally different use case and so doesn't relate to the first tutorial in the series any longer (which used the flutter default counter app). So all in all this series no longer flows together :-(

  • @simransingh1507
    @simransingh1507 5 років тому

    Great Work. I think it would be better if you create flutter tutorials in Android Studio. It has great support with the latest version. :)

    • @ResoCoder
      @ResoCoder  5 років тому +6

      I feel like Android Studio is too bloated for what it is. Flutter doesn't need a heavy IDE, at least in my experience - and I'm coming from native Android development so I made a conscious switch to VS Code.

    • @aislanarislou
      @aislanarislou 5 років тому

      @@ResoCoder I agree!! Android Studio is bloated as hell... and heavy.

  • @andreykaok9497
    @andreykaok9497 5 років тому +1

    Little (but important) changes ;) to be working with flutter_bloc: ^0.5.4 ^0.6.0 etc.
    gist.github.com/ruan65/41d1aa37402e49eea065c5bbe0698853

    • @kuestua
      @kuestua 5 років тому

      thanks! this worked!

  • @millerliang3565
    @millerliang3565 5 років тому

    WHERE IS THE BLOCBUILDER WIDGET!!!!!!

  • @vasilvasilich8224
    @vasilvasilich8224 3 роки тому

    You can try this library with generic approach for cooking graphql_flutter + bloc
    pub.dev/packages/graphql_flutter_bloc

  • @mohammadhosseinramezanzade9675
    @mohammadhosseinramezanzade9675 4 роки тому

    you used an old version of Bloc.

  • @bazoozoo1186
    @bazoozoo1186 4 роки тому +2

    frankly, I hate it.
    it looks so over-complicated... and that Bloc object sending events to itself... yuck!
    scoped_model framework looks much less cluttered.

  • @thatsenam9183
    @thatsenam9183 4 роки тому

    Its complicated

  • @edwardnjoroge5222
    @edwardnjoroge5222 5 років тому

    Play at 1.75 speed. You're welcome.

    • @ResoCoder
      @ResoCoder  5 років тому +1

      I watch everything at 2x

  • @AbdulmalikHamid
    @AbdulmalikHamid 5 років тому

    This is the best bloc tutorial EVER!