Flutter 之 AppBar 负值偏移设置

1,945 阅读1分钟

当前效果,因为嵌套的网页有自己的导航条,当前代码如下

class NewsDetailPage extends StatefulWidget {
  NewsDetailPage({Key key, this.title, this.newsUrl}) : super(key: key);
  final String title;
  final String newsUrl;
  @override
  _NewsDetailPageState createState() => _NewsDetailPageState();
}

class _NewsDetailPageState extends State<NewsDetailPage> {
  WebViewController _controller;
  Widget webView() {
    return WebView(
      initialUrl: "${widget.newsUrl}",
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
      },
    );
  }

  Widget shareButton() {
    return IconButton(
        icon: Icon(Icons.share),
        onPressed: () {
          Share.share('${widget.title} : ${widget.newsUrl}');
        });
  }

  Widget appBar() {
    return AppBar(
      backgroundColor: Colors.white,
      title: Text(
        widget.title,
        style: TextStyle(color: Colors.black),
      ),
      leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Routes.goBack(context);
          }),
      actions: <Widget>[shareButton()],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      body: Container(
          margin: EdgeInsets.only(top: 0),
          child: webView()),
    );
  }
}

现在想把网页自带的导航条隐藏起来,需要把下部的webview向上偏移,使AppBar能将webView的导航条覆盖住,这样就能实现我们想要的效果

幸好:Container有个transform属性,我们可以这样设置body里面的webview

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      body: Container(
          margin: EdgeInsets.only(top: 0),
          child: Container(
            transform: Matrix4.translationValues(0, -44, 0.0),
            child: webView(),
          )),
    );
  }

ok,解决。 对于我们需要的其他需要偏移负数,且无法使用Stack时候,可以借鉴这个思路。