Flutter 不用Scaffold.of(context)来显示SnackBar,直接用GlobalKey来访问

由于Flutter 的SnackBar必须依赖于Scaffold.of(context),而要访问正确的context,必须要严格的套层级或者传参context,这样会有一些弊端,在一个函数内套过多层级会让代码维护非常困难,传参对于多个回调事件call也很麻烦,这时可以采用GlobalKey来直接访问,而不用Scaffold.of(context)。

 

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  final _scaffoldKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('SnackBar Demo'),
      ),
      body: Center(
        child: RaisedButton(
          color: Colors.pink,
          textColor: Colors.white,
          onPressed: _displaySnackBar(context),
          child: Text('Display SnackBar'),
        ),
      ),
    );
  }

  _displaySnackBar(BuildContext context) {
    _scaffoldKey.currentState.showSnackBar(
      SnackBar(
        content: Text('Are you talkin\' to me?'),
      ),
    );
  }
}

你可能感兴趣的:(APP)