Navigator.push在子页面中使用正常,但当我将其放在主页面时,出现错误。

huangapple go评论64阅读模式
英文:

I am using Navigator.push it works in the child page, but when I put it in main its giving an error

问题

以下是您提供的代码的翻译部分:

main.dart:

import 'package:flutter/material.dart';
import 'package:questionx/theme/header.dart';
import "package:questionx/second.dart";

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Application',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: const AppHeader(
        title: "Home Page",
        titleWidget: Icon(Icons.access_time),
        leading: Icon(
          Icons.home,
          color: Colors.black,
        ),
        showActionIcon: true,
        onMenuActionTap: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const SecondPage()));
        },
      ),

      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

header.dart:

import "package:flutter/material.dart";

class AppHeader extends StatelessWidget implements PreferredSizeWidget {
  const AppHeader({
    Key? key,
    this.title = '',
    this.leading,
    this.titleWidget,
    this.showActionIcon = false,
    this.onMenuActionTap,
  }) : super(key: key);

  final String title;
  final Widget? leading;
  final Widget? titleWidget;
  final bool showActionIcon;
  final VoidCallback? onMenuActionTap;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 25 / 2.5),
      child: Stack(
        children: [
          Positioned.fill(
              child: titleWidget == null
                  ? Center(
                      child: Text(title,
                          style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: Colors.white)))
                  : Center(child: titleWidget!)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              leading ??
                  Transform.translate(
                    offset: const Offset(-14, 0),
                    child: const Icon(
                      Icons.menu,
                      color: Colors.amber,
                    ),
                  ),
              if (showActionIcon)
                Transform.translate(
                  offset: const Offset(10, 0),
                  child: InkWell(
                      onTap: onMenuActionTap,
                      child: const Padding(
                        padding: EdgeInsets.all(10.0),
                        child: Icon(Icons.menu),
                      )),
                )
            ],
          )
        ],
      ),
    ));
  }

  @override
  Size get preferredSize => const Size(double.maxFinite, 80);
}

second.dart:

import 'package:flutter/material.dart';
import 'package:questionx/theme/header.dart';

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppHeader(
          leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const BackButton())),
      body: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

希望这可以帮助您解决问题。如果您需要进一步的帮助,请随时提出。

英文:

I am trying to use Navigator.push to navigate to a child component. when I use this in header component under onTap this works as expected but I am trying to bring to main it fails. any help is appreciated

main.dart

import &#39;package:flutter/material.dart&#39;;
import &#39;package:questionx/theme/header.dart&#39;;
import &quot;package:questionx/second.dart&quot;;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Application&#39;,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: const MyHomePage(title: &#39;Flutter&#39;),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}
class _MyHomePageState extends State&lt;MyHomePage&gt; {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: const AppHeader(
title: &quot;Home Page&quot;,
titleWidget: Icon(Icons.access_time),
leading: Icon(
Icons.home,
color: Colors.black,
),
showActionIcon: true,
onMenuActionTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =&gt; const SecondPage()));
},
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: &lt;Widget&gt;[
const Text(
&#39;You have pushed the button this many times:&#39;,
),
Text(
&#39;$_counter&#39;,
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: &#39;Increment&#39;,
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

header.dart

import &quot;package:flutter/material.dart&quot;;
class AppHeader extends StatelessWidget implements PreferredSizeWidget {
const AppHeader({
Key? key,
this.title = &#39;&#39;,
this.leading,
this.titleWidget,
this.showActionIcon = false,
this.onMenuActionTap,
}) : super(key: key);
final String title;
final Widget? leading;
final Widget? titleWidget;
final bool showActionIcon;
final VoidCallback? onMenuActionTap;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 25 / 2.5),
child: Stack(
children: [
Positioned.fill(
child: titleWidget == null
? Center(
child: Text(title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.white)))
: Center(child: titleWidget!)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
leading ??
Transform.translate(
offset: const Offset(-14, 0),
child: const Icon(
Icons.menu,
color: Colors.amber,
),
),
if (showActionIcon)
Transform.translate(
offset: const Offset(10, 0),
child: InkWell(
onTap: onMenuActionTap,
child: const Padding(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.menu),
)),
)
],
)
],
),
));
}
@override
Size get preferredSize =&gt; const Size(double.maxFinite, 80);
}

second.dart

import &#39;package:flutter/material.dart&#39;;
import &#39;package:questionx/theme/header.dart&#39;;
class SecondPage extends StatelessWidget {
const SecondPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppHeader(
leading: IconButton(
onPressed: () =&gt; Navigator.pop(context),
icon: const BackButton())),
body: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: &lt;Widget&gt;[
Text(
&#39;You have pushed the button this many times:&#39;,
),
],
),
),
);
}
}

I have tried to make changes to onMenuActionTap in main but any change that make is not yielding in a right code

答案1

得分: 0

使用Builder小部件将您的Scaffold小部件封装起来,它将正常工作。它在主函数中不起作用的原因是因为小部件树。因为您的小部件不是父小部件的子小部件,所以会引发错误。

英文:

Encapsulate your Scaffold widget with Builder widget and it will work. The reason that it does not work in main is because of widget tree. Because your widget is not the child of parent widget, it throws an error.

huangapple
  • 本文由 发表于 2023年7月27日 20:55:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定