![](/img/trans.png)
[英]Flutter Riverpod context.read vs Provider in the build method
[英]Flutter BloC couldn't find correct provider when context.read is called
我是Flutter和BloC的新手,所以我想創建一個項目來提高我對它們的了解。
在下方您可以看到 dart 個文件。
bnb_cubit.dart
class AppBottomNavigationBarCubit extends Cubit<AppBottomNavigationBarState> {
AppBottomNavigationBarCubit()
: super(AppBottomNavigationBarState(selectedIndex: 0));
void change(int index) =>
emit(AppBottomNavigationBarState(selectedIndex: index));
}
bnb_state.dart
class AppBottomNavigationBarState {
int selectedIndex;
AppBottomNavigationBarState({required this.selectedIndex});
}
bnb.dart
class AppBottomNavigationBar extends StatelessWidget {
AppBottomNavigationBar({super.key});
final List<Widget> screens = [HomeScreen(), SearchScreen(), LibraryScreen()];
@override
Widget build(BuildContext context) {
return BlocBuilder<AppBottomNavigationBarCubit,
AppBottomNavigationBarState>(
builder: (context, state) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: "Home",
),
BottomNavigationBarItem(
icon: Icon(Icons.library_books),
label: "Home",
),
],
onTap: (value) {
context.read<AppBottomNavigationBarCubit>().change(value);
},
currentIndex:
context.read<AppBottomNavigationBarState>().selectedIndex,
),
body: screens[state.selectedIndex],
);
},
);
}
}
主要.dart
Future<void> main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<AppBottomNavigationBarCubit>(
create: (context) => AppBottomNavigationBarCubit(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AppBottomNavigationBar(),
),
);
}
}
在bnb.dart文件中,如果我使用
context.read<AppBottomNavigationBarState>().selectedIndex
要更改BottomNavigationBar的currentIndex字段,應用程序會拋出:
The following ProviderNotFoundException was thrown building
BlocBuilder<AppBottomNavigationBarCubit,
AppBottomNavigationBarState>
但是,如果我將該行更改為
state.selectedIndex
它工作正常,我想知道為什么會這樣。
我的第二個問題是,您會使用BloC來創建BottomNavigationBar嗎?
提前致謝!
您需要閱讀AppBottomNavigationBarCubit
以獲取當前的 state。
所以它會是
currentIndex:
context.read<AppBottomNavigationBarCubit>().state.selectedIndex,
您應該使用Cubit
訪問它
context.read<AppBottomNavigationBarCubit>().state.selectedIndex
不是State
context.read<AppBottomNavigationBarState>()
由於您只提供AppBottomNavigationBarCubit
而不是AppBottomNavigationBarState
:
return BlocProvider<AppBottomNavigationBarCubit>()
您遇到錯誤couldn't find correct provider
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.