gpt4 book ai didi

dart - 如何防止传递 BuildContext?

转载 作者:IT王子 更新时间:2023-10-29 06:48:12 24 4
gpt4 key购买 nike

目前我从 HomeScreenbuild 方法中获取 BuildContext,然后我必须将它传递给 _gridSliver 然后向下到 _storeCard

我如何编写代码才能不需要向下传递上下文?

也许我可以创建一个名为 _StoreCard 的新私有(private) StatelessWidget,它有自己的 build 方法,因此也有自己的 BuildContext?

class HomeScreen extends StatelessWidget {
HomeScreen({Key key}) : super(key: key);

@override
Widget build(BuildContext context) {
return StoreConnector<AppState, List<MyStore.Store>>(
converter: (Store<AppState> store) => store.state.home.stores,
builder: (BuildContext context, List<MyStore.Store> stores) =>
CustomScrollView(slivers: <Widget>[_gridSliver(stores, context)]));
}

Widget _gridSliver(stores, context) {
return SliverGrid(
delegate: SliverChildListDelegate(List<Widget>.from(stores.map(_storeCard, context))));
}

Widget _storeCard(MyStore.Store store, BuildContext context) {
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => StoreScreen(storeId: store.id)),
);
},
child: Container(child: Text(store.name))
);
}
}

此问题的另一个实例是我在子函数上导航。

@override
Widget build(BuildContext context) {
return Column(
children: [
WhiteButton(text: "Login with Facebook", onPressed: _loginWithFacebook),
WhiteButton(text: "Login with Google", onPressed: _loginWithGoogle),
])
)
}

_loginWithFacebook(context) async {
...
var user = User.fromFacebook(result.accessToken.token, json.decode(graphResponse.body));
await _login(user, context);
}
}

_loginWithGoogle(context) async {
...
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
await _login(User.fromGoogle(googleUser), context);
}

_login(user, context) async {
var fetchedUser = await MeService.getUser(user);
if (fetchedUser != null) {
loginSuccess(fetchedUser);
Navigator.popUntil(context, ModalRoute.withName(MainRoutes.root));
} else {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => RegisterScreen(user: user)),
);
}
}

最佳答案

要获得一个新的BuildContext,您有两个主要的解决方案:

  • 将子树的一部分提取到一个新的小部件中,通常是 StatelessWidget。然后使用 build 方法中的 BuildContext

  • 使用 Builder 小部件,它基本上是一个可重用的小部件,用于获取 BuildContext:

例子:

 @override
Widget build(BuildContext context) {
return Builder(
builder: (context) {
// do something with this new context
},
);
}

关于dart - 如何防止传递 BuildContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com