Don't use 'BuildContext's across async gaps. flutter警告
时间: 2023-12-02 08:03:56 浏览: 80
flutter_demo_async.zip
5星 · 资源好评率100%
The `Don't use 'BuildContext's across async gaps` warning in Flutter is usually caused by using a `BuildContext` that was obtained in a different `async` context than the one in which it is being used. This can lead to unexpected behavior and errors.
To avoid this warning, you can use the `BuildContext` obtained in the current `async` context or pass it as a parameter to the function or method where it is needed. Here's an example of how to do this:
```dart
Future<void> showSnackBar(BuildContext context, String message) async {
final snackBar = SnackBar(content: Text(message));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('SnackBar Demo')),
body: Center(
child: ElevatedButton(
child: Text('Show SnackBar'),
onPressed: () {
showSnackBar(context, 'Hello, World!');
},
),
),
),
);
}
}
```
In the example above, we define a function `showSnackBar` that takes a `BuildContext` and a `String` as parameters. We use the `ScaffoldMessenger.of(context)` method to obtain the `ScaffoldMessengerState` for the current `BuildContext` and show the `SnackBar`.
In the `onPressed` callback of the `ElevatedButton`, we pass the `BuildContext` obtained from the `build` method to the `showSnackBar` function. This ensures that we're using the `BuildContext` obtained in the current `async` context, and avoids the warning message.
阅读全文