我是新的扑和扑集团。我正试着准备一个例子,我在屏幕上有一个灯泡和一个开关。我的想法是当我按下开关时发光Buld,当我再次按下开关时把它关掉。我有两个图像,每个buld和开关的开/关。我的代码不起作用,不知道哪里出错了。这是我的代码
主,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,
),
),
),
),
],
);
},
),
),
),
),
);
}
}
字符串
球块镖
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));
});
}
}
型
球态镖
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];
}
型
灯泡事件
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 {}
型
x1c 0d1x的数据
为什么代码不起作用
3条答案
按热度按时间z4iuyo4d1#
当灯亮着,他们轻敲开关,你想把灯关掉。你把这些弄反了。
字符串
khbbv19g2#
尝试改变你的你的手势检测器如下所述
字符串
和bulb_bloc.dart
型
gab6jxml3#
您可以在main.dart文件中进行一些更改:
字符串