flutter 无法弹出 snackbar 的解决办法

最近在玩flutter,遇到了snackbar弹不出的情况,log显示这个

显示不出 snackbar 的代码差不多长这样,由于我的代码高亮插件不支持dartlang,就用java代替一下了。。

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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: RaisedButton(
        onPressed: () {
          print("Tap");
          Scaffold.of(context)
          .showSnackBar(new SnackBar(content: Text('Test')));
        },
        child: new Container(
          padding: new EdgeInsets.all(12.0),
          child: new Text('Flat Button'),
        ),
      )),
    );
  }
}

我的解决解决方法是,新建个snackbar类,内容如下。

import 'package:flutter/material.dart';

class snackBar {
  static SnackBarByKey(final GlobalKey scaffoldkey,
      BuildContext context, String str) {
    final snackBar = new SnackBar(content: new Text(str));
    scaffoldkey.currentState.showSnackBar(snackBar);
  }
}

然后在 main.dart import 这个文件,再修改一下代码,添加一个globalkey,改成这样

import 'package:flutter/material.dart';
import './snackbar.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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  GlobalKey scaffoldKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: RaisedButton(
        onPressed: () {
          snackBar.SnackBarByKey(scaffoldKey, context, "Test");
          // print("Tap");
          // Scaffold.of(context)
          //     .showSnackBar(new SnackBar(content: Text('Test')));
        },
        child: new Container(
          padding: new EdgeInsets.all(12.0),
          child: new Text('Flat Button'),
        ),
      )),
    );
  }
}

这样就可以了,就是增加了第2、28、33、40行的代码而已,效果如下。

为啥这dart的自动格式化是2空格的缩进,异端啊….

flutter 无法弹出 snackbar 的解决办法》上有1条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注