Flutter SnackBar显示没有Scaffold

1
Scaffold.of() called with a context that does not contain a Scaffold.

原因:context层级使用错误,一般是直接使用页面级的context导致错误

1
page -> Scaffold -> Button => 使用page级context导致错误

解决:中间嵌套一个Builder,用于”转换”出一个位于Scaffold后的context

1
page -> Scaffold -> Builder(new context) -> Button
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(
title: Text('测试'),
elevation: 0.0,
),
body: Container(
child: Builder(
//嵌套Builder
builder: (ctx) => RaisedButton(
onPressed: () => _click(ctx), //将Builder给的ctx传递给方法
)),
),
);
}

void _click(BuildContext context) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('内容'),
));
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :