[英]flutter bloc: variable is not defined in BlocBuilder
I am trying to use Flutter bloc in my project.After creating State and Event class in State i have a LanguageLoad
class: I am trying to use Flutter bloc in my project.After creating State and Event class in State i have a LanguageLoad
class:
abstract class LanguageState extends Equatable {
const LanguageState();
@override
List<Object> get props => [];
}
class LanguageInitial extends LanguageState {}
class LanguageLoad extends LanguageState {
final Locale locale;
LanguageLoad(this.locale);
@override
List<Object> get props => [locale];
}
After creating bloc class i am using in main class:创建块 class 后,我在主要 class 中使用:
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(
BlocProvider(
create: (_) => LanguageBloc()..add(LanguageLoadStarted()),
child: MyApp()),
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<LanguageBloc, LanguageState>(
builder: (context, languageState) => MaterialApp(
debugShowCheckedModeBanner: false,
locale: languageState.locale, // locale is not defined
}
But I don't know why locale is not defined in locale: languageState.locale
?但我不知道为什么 locale 没有在locale: languageState.locale
中定义?
You don't know the type of languageState
and you need to cast it to obtain locale
value.您不知道languageState
的类型,您需要对其进行强制转换以获得locale
值。 This is a piece of my in production app:这是我的生产应用程序的一部分:
BlocBuilder<LanguageBloc, LanguageState>(
builder: (context, state) {
Locale locale;
if (state is LanguageLoaded) {
locale = state.locale;
}
return MaterialApp(
locale: locale,
In my case I load MaterialApp
even if Locale first time is null.在我的情况下,即使第一次区域设置是 null,我也会加载MaterialApp
。 It depends by you app logic.这取决于您的应用程序逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.