如何解决 Flutter 中 onPressed 的问题?

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

我是 Flutter 编程新手,在导航到新页面并使 onPressed 正常工作时遇到问题。我正在使用下面的代码片段,并且我已经看到其他教程视频做了同样的事情,但是当我使用该代码片段时,“() { Navigator.push( ..... ); }”中的所有内容都会以红色下划线显示出现错误:

无效常量值.dart(invalid_constant)

我不确定如何修复此错误,我们将不胜感激,谢谢。

const ListTile(
              title: Text('About Me'),
              subtitle: Text('Account Information'),
              trailing: IconButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const About()),
                  );
                },
                icon: Icon(Icons.keyboard_arrow_right_rounded),
              ),
            ),
flutter dart
4个回答
0
投票

该错误与 ListTile onTap 属性有关。

Widget ListTile 已经定义了 onTap,因此 IconButton 中的 onPressed 属性将never被触发。

试试这个:

ListTile(
  title: const Text('About Me'),
  subtitle: const Text('Account Information'),
  onTap: () {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => const About()),
    );
  },
  trailing: const Icon(Icons.keyboard_arrow_right_rounded,),

0
投票

尝试删除 ListTile 附近的关键字

const
。如果
About
的构造函数不是
const
,也将其从
push
方法中删除。


0
投票

目前,dart 函数不支持常量文字。您试图使 ListTile 成为常量构造函数,但 onPressed 将函数作为参数,该函数不能是常量或最终的。从 ListTile 中删除 const 或创建另一个静态函数,然后将其传递给 onPressed。

您可以通过以下链接查看。

https://github.com/dart-lang/language/issues/1048

您还可以使用 NavigatorState 进行导航。

   class MyApp2 extends StatelessWidget {
    
      static final navigatorStateKey = GlobalKey<NavigatorState>();
      const MyApp2({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
           key: navigatorStateKey,
           home: ListView(
             children: List.generate(20, (index) =>
                 const ListTile(
                  title: Text('About Me'),
                  subtitle: Text('Account Information'),
                  trailing: IconButton(
                    onPressed:  onPressed,
                   icon: Icon(Icons.keyboard_arrow_right_rounded),
                  ),
                ),
            ),
          ),
        );
    
      }
      static void onPressed() {
        MyApp2.navigatorStateKey.currentState.push( 
      MaterialPageRoute(builder: (context) => const About()));
       }
      }

0
投票

const 
中删除
ListTile 
关键字。

现在您的列表不是静态或固定的,它可能会更改或对

onPressed 
执行某些操作。所以widget不能用const标记 在这种情况下。

这适用于所有小部件。动态小部件不适用于

const 
关键字

ListTile(
      title: const Text('About Me'),
      subtitle: const Text('Account Information'),
      trailing: IconButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const About()),
          );
        },
        icon: const Icon(Icons.keyboard_arrow_right_rounded),
      ),
    ),
© www.soinside.com 2019 - 2024. All rights reserved.