参数为 null 而不是带有 ModalRoute.of() 的 id

Parameter is null instead of an id with ModalRoute.of()

我正在使用 Flutter 和 Firebase 开发移动应用程序。

我正在尝试使用 pushNamed() 并传递一个参数。 (一个id)

我不知道如何解决我的问题。

这是我的代码:

@override
  void didChangeDependencies() {
    if (_isInit) {
      print(ModalRoute.of(context).settings.arguments);
      final productId = ModalRoute.of(context).settings.arguments;
      if (productId != null) {
        _editedAngebot = Provider.of<Angebote>(context).findByID(productId);
        _initValues = {
          'titel': _editedAngebot.titel,
          'beschreibung': _editedAngebot.beschreibung,
          'semester': _editedAngebot.semester.toString(),
          'fach': _editedAngebot.fach,
          'abteilung': _editedAngebot.abteilung,
        };
      }
    }
    _isInit = false;
    super.didChangeDependencies();
  }

和另一个class,我在这里设置了参数。我的“Angebot”对象只有一个默认构造函数。

trailing: isAllowed()
            ? IconButton(
                icon: Icon(Icons.edit),
                onPressed: () {
                  Navigator.of(context).maybePop();
                  Navigator.of(context)
                      .pushNamed('/editAngebot', arguments: id);
                })

为什么我的ID是空的?

您的Id为空,因为您是先弹出页面再推送新页面。

使用 pushReplacementNamed()

这是一个代码示例

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: FirstPage(),
      routes:{
        Secondpage.routeName:(context)=>Secondpage(),
      }
    );
  }
}

class FirstPage extends StatelessWidget {
  final String id = '01';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child:ElevatedButton(
        child: Text('GoTo secondPage'),
        onPressed: (){
          Navigator.of(context).pushReplacementNamed(Secondpage.routeName,arguments: id);
        },
      ))
    );
  }
}

class Secondpage extends StatelessWidget {
  static const routeName = 'secondpage';
  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context).settings.arguments as String;
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(child:Text('$data')),
          ElevatedButton(
        child: Text('GoTo FirstPage'),
        onPressed: (){
          Navigator.of(context).pop();
        },
      )
        ],
      )
    );
  }
}

您可能应该将 class 中定义的 id 更改为动态类型,它会起作用。经过测试,它可以正常工作

class Product with ChangeNotifier {
  //changed to dynamic as errors with null and string came topping up

  final dynamic id;
  final String title;
  final String description;
 

  Product(
      {required this.id,
      required this.title,
      required this.description,
    });