flutter - 处理手势时引发了以下断言: Scaffold.of() 使用不包含 Scaffold 的上下文调用
问题描述
import 'package:flutter/material.dart';
import 'dashboard.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.accessible),
onPressed: () => Scaffold.of(context).openEndDrawer(),
),
title: Text('Sorted.'),
backgroundColor: Color(0xff0A3D62),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
new UserAccountsDrawerHeader(
accountName: new Text('XYZ'),
accountEmail: new Text('XYZ@gmail.com'),
currentAccountPicture: new CircleAvatar(),
)
],
),
),
body: Center(child: Home()),
),
),
);
}
}
错误:
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.
当我尝试从图标打开抽屉时会触发错误。请帮我解决这个问题。提前致谢!
解决方案
@rkdupr0n 说您的context
变量没有Scaffold
祖先是正确的。context
当前指的是外部build
函数传递的内容,它没有Scaffold
作为祖先,它只包含它。因此,您需要获得一个具有在您的树中BuildContext
已有的脚手架作为其祖先的脚手架。Scaffold
为此,您可以使用Builder
小部件来包装需要此上下文的区域:
AppBar(
leading: Builder(
builder: (context) {//NEW CONTEXT OBTAINED HERE
return IconButton(
icon: Icon(Icons.accessible),
onPressed: () => Scaffold.of(context).openEndDrawer(),
);
}
),
...
),
推荐阅读
- can-bus - CAN总线从两个平衡的主机发送数据
- node.js - 限制并发请求 + node.js
- php - PHP 警告:shell_exec(): 无法执行 '[command]'
- javascript - 为什么 Chrome Mobile 取消 setPointerCapture?我如何解决它?
- linux - 转换后将文件移动到其原始位置
- mongodb - MongoDB mongoose findOneAndUpdate() Await 不等待。A3 在 A2 之前运行
- laravel - Laravel API:“错误:证书已过期”虽然证书处于活动状态
- windows - 如何将命令行参数传递给由 doskey 调用的 PowerShell 脚本
- php - 在 PHP 7 中根据包含日期的值删除数组元素
- c# - 在 ASP.Net Web API 控制器中具有相同路由名称的 Post Action 方法重载