标签:extend 就是 less hat tor out not ges center
当我们想showSnackBar的时候,需要通过Scaffold.of(context)得到Scaffold。但是如果这个context用错的话,flutter就会抛出错误。下面我们通过代码仔细看一下。
import ‘package:flutter/material.dart‘;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: OutlineButton(
child: Text("SnackBar"),
onPressed: () {
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Show SnackBar")));
},
),
),
),
);
}
}
当我们点击OutlineButton时,会如以下的错误:
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
原因是Scaffold.of(context)这个方法的context是MyApp组件的context,它不能得到子组件Scaffold。
整体方案就是Scaffold.of(context)里面的context得是Scaffold子组件的context,这样我们有两种方式实现。
import ‘package:flutter/material.dart‘;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext buildContext) {
return Center(
child: OutlineButton(
child: Text("SnackBar"),
onPressed: () {
Scaffold.of(buildContext).showSnackBar(SnackBar(content: Text("Show SnackBar")));
},
),
);
},
),
),
);
}
}
import ‘package:flutter/material.dart‘;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(body: HomeWidget()),
);
}
}
class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: OutlineButton(
child: Text("SnackBar"),
onPressed: () {
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Show SnackBar")));
},
),
);
}
}
鼠标放在widget上面或者选中该widget。mac上面
flutter question---->Scaffold.of(context)
标签:extend 就是 less hat tor out not ges center
原文地址:https://www.cnblogs.com/huhx/p/13208638.html