全屏浏览
缩小浏览
回到页首

flutter issue---->Scaffold.of(context)

当我们想showSnackBar的时候,需要通过Scaffold.of(context)得到Scaffold。但是如果这个context用错的话,flutter就会抛出错误。下面我们通过代码仔细看一下。

issue code

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.

issue reason

原因是Scaffold.of(context)这个方法的context是MyApp组件的,它不能得到子组件Scaffold。因为widget从上到下,父组件的context是得不到子组件的。

issue fixed

整体方案就是Scaffold.of(context)里面的context得是Scaffold子组件的context,这样我们有两种方式实现。

  • use Builder widget
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")));
                },
              ),
            );
          },
        ),
      ),
    );
  }
}
  • extract as child widget
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")));
        },
      ),
    );
  }
}

shortcut to extract widget

鼠标放在widget上面或者选中该widget。mac上面

  • option+command+w。
  • Refactor->Extract->Extract Flutter Widget(Menu or Right click)

posted @ 2020-06-29 16:30  huhx  阅读(810)  评论(0编辑  收藏  举报