簡體   English   中英

處理手勢時引發了以下斷言: Scaffold.of() 使用不包含 Scaffold 的上下文調用

[英]The following assertion was thrown while handling a gesture: Scaffold.of() called with a context that does not contain a 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 function 傳遞的內容,它沒有Scaffold作為祖先,它只包含它。 因此,您需要獲得一個BuildContext ,它具有Scaffold您在樹中已經擁有的腳手架,因為它是祖先。 為此,您可以使用Builder小部件來包裝需要此上下文的區域:

AppBar(
  leading: Builder(
    builder: (context) {//NEW CONTEXT OBTAINED HERE
      return IconButton(
        icon: Icon(Icons.accessible),
        onPressed: () => Scaffold.of(context).openEndDrawer(),
      );
    }
  ),
  ...
),  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM