导航器中未定义上下文,等等

问题描述 投票:0回答:1

我正在创建一个可在多个页面上使用的自定义AppBar。 customappbar.dart

class CustomAppBar extends AppBar {
  CustomAppBar({Key key, Widget title})
      : super(
          key: key,
          title: title,
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.directions_car),
              onPressed: () {
                Navigator.push(
                  context, //UNDEFINED
                  MaterialPageRoute(
                    builder: (context) => NewPage(),
                  ),
                );
              },
            ),
          ],
        );
}

这里是个例子。 newpage.dart

class _ NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CashOnHandAppBar(
        title: Text('New Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[],
        ),
      ),
    );
  }
}

上下文变得不确定。缺少构建方法吗?

flutter
1个回答
0
投票

您正在扩展AppBar类,它不适用于自定义应用栏,您必须扩展StatelessWidget并为自定义应用栏实现PreferredSizeWidget类这是自定义应用栏的工作示例:-

import 'package:flutter/material.dart';

class SimpleAppBar extends StatelessWidget implements PreferredSizeWidget {
  final String _title;
  final bool centerTitle;

  SimpleAppBar(this._title, {this.centerTitle = false, Key key})
      : preferredSize = Size.fromHeight(56.0),
        super(key: key);

  @override
  final Size preferredSize; // default is 56.0

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text(_title),
      centerTitle: centerTitle,
    );
  }
}

并且不是将函数直接添加到自定义appbar中,而是将对类构造函数的函数引用传递给需要通过下面的函数添加参考:-

onPressed: () {
            Navigator.push(
              context, //UNDEFINED
              MaterialPageRoute(
                builder: (context) => NewPage(),
              ),
© www.soinside.com 2019 - 2024. All rights reserved.