T
T
trickster20192022-03-09 07:36:40
Dart
trickster2019, 2022-03-09 07:36:40

Has anyone had any errors while working with onGenerateRoute?

when trying to transfer data to the second screen (SecondHome), the error "Expected a value of type "User", but got one of type ''Null'" occurs, it seems like I passed values ​​to user and in SecondHome itself and in onGenerateRoute, but all the same an error is thrown.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: FirstHome(),
    onGenerateRoute: (settings) {
      if (settings.name == '/second') {
        final user = settings.arguments as User;
        return MaterialPageRoute(builder: (context) => SecondHome(user: user));
      }
      return null;
    },
  ));
}

class FirstHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Home'),
        centerTitle: true,
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            User user = User(name: "Aboba", age: 33);
            Navigator.pushNamed(context, "/second", arguments: user);
          },
          child: Text('Second Home'),
        ),
      ),
    );
  }
}

class SecondHome extends StatelessWidget {
  late final User user;
  SecondHome({required this.user});

  @override
  Widget build(BuildContext context) {
   
    RouteSettings settings = ModalRoute.of(context)!.settings;

    user = settings.arguments as User;
    return Scaffold(
      appBar: AppBar(
        title: Text('${this.user.name} - ${this.user.age}'),
        centerTitle: true,
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go Back'),
        ),
      ),
    );
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
andrew8712, 2022-03-10
@trickster2019

```
RouteSettings settings = ModalRoute.of(context)!.settings;
user = settings.arguments as User;
```
These lines are not needed, they should be removed. `user` is already passed to the widget constructor, there is no point in trying to pull it out of `ModalRoute`.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question