skip to Main Content

I am new to flutter and flutter bloc. I am trying to prepare an example, where i have a bulb and a switch on the screen. My idea is to glow the buld when i press the switch and put it off when i press the switch again. I have two images each for buld and switch on/off. My code doesnt work, dont know where i am getting it wrong. Here is my code

Main,dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'blocs/bulb/bulb_bloc.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: BlocProvider(
            create: (context) => BulbBloc(),
            child: BlocBuilder<BulbBloc, BulbState>(
              builder: (context, state) {
                String bulbImgSrc = state.isOn
                    ? 'assets/images/turned-on.png'
                    : 'assets/images/turned-off.png';
                String switchImgSrc = state.isOn
                    ? 'assets/images/switch-on.png'
                    : 'assets/images/switch-off.png';
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Container(
                      width: 200,
                      height: 200,
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        image: DecorationImage(
                          image: AssetImage(bulbImgSrc),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        print('Tapped');
                        state.isOn
                            ? context.read<BulbBloc>().add(BulbOnEvent())
                            : context.read<BulbBloc>().add(BulbOffEvent());
                      },
                      child: Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          color: Colors.transparent,
                          image: DecorationImage(
                            image: AssetImage(switchImgSrc),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

bulb_bloc.dart

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';

part 'bulb_event.dart';

part 'bulb_state.dart';

class BulbBloc extends Bloc<BulbEvent, BulbState> {
  BulbBloc() : super(BulbState.initial()) {
    on<BulbOffEvent>((event, emit) {
      emit(const BulbState(false));
    });
    on<BulbOnEvent>((event, emit) {
      emit(const BulbState(true));
    });
  }
}

bulb_state.dart

part of 'bulb_bloc.dart';

class BulbState extends Equatable {
  final bool isOn;

  const BulbState(this.isOn);

  factory BulbState.initial() => const BulbState(false);

  @override
  // TODO: implement props
  List<Object?> get props => [isOn];
}

bulb_event.dart

part of 'bulb_bloc.dart';

class BulbEvent extends Equatable {
  const BulbEvent();

  @override
  // TODO: implement props
  List<Object?> get props => [];
}

class BulbOnEvent extends BulbEvent {}

class BulbOffEvent extends BulbEvent {}

enter image description here

Why the code is not functioning

3

Answers


  1. You can some change in you main.dart file :

    @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: BlocProvider(
                create: (context) => BulbBloc(),
                child: BlocBuilder<BulbBloc, BulbState>(
                  builder: (context, state) {
                     String bulbImgSrc = state.isOn
                    ? 'assets/images/turned-on.png'
                    : 'assets/images/turned-off.png';
                String switchImgSrc = state.isOn
                    ? 'assets/images/switch-on.png'
                    : 'assets/images/switch-off.png';
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Container(
                          width: 200,
                          height: 200,
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            image: DecorationImage(
                              image: AssetImage(bulbImgSrc),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            print('Tapped');
                            bool isOn = context.read<BulbBloc>().state.isOn;
                            if (isOn) {
                              context.read<BulbBloc>().add(BulbOffEvent());
                              setState(() {
                                bulbImgSrc = 'assets/images/turned-off.png';
                              });
                            } else {
                              context.read<BulbBloc>().add(BulbOnEvent());
                              setState(() {
                                bulbImgSrc = 'assets/images/turned-on.png';
                              });
                            }
                          },
                          child: Container(
                            width: 100,
                            height: 100,
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                              image: DecorationImage(
                                image: AssetImage(switchImgSrc),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              ),
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Try to change your your gesture detector as mentioned below

                      GestureDetector(
                          onTap: () {
                            print('Tapped');
                            state.isOn
                                ? BlocProvider.of<BulbBloc>(context)
                                    .add(BulbOnEvent())
                                : BlocProvider.of<BulbBloc>(context)
                                    .add(BulbOffEvent());
                          },
    

    and bulb_bloc.dart

    import 'dart:async';
    
    import 'package:bloc/bloc.dart';
    import 'package:equatable/equatable.dart';
    
    part 'bulb_event.dart';
    
    part 'bulb_state.dart';
    
    class BulbBloc extends Bloc<BulbEvent, BulbState> {
      BulbBloc() : super(BulbState.initial()) {
        on<BulbOffEvent>((event, emit) {
          emit(BulbState(true));
        });
        on<BulbOnEvent>((event, emit) {
          emit(BulbState(false));
        });
      }
    }
    
    Login or Signup to reply.
  3. When the light is on and they tap the switch you want to turn the light off. You had these reversed.

    state.isOn
     ? context.read<BulbBloc>().add(BulbOffEvent()) 
     : context.read<BulbBloc>().add(BulbOnEvent());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search