pushReplacementNamed некорректно работает в Drawer - PullRequest
0 голосов
/ 09 мая 2020

Я новичок в флаттере и делаю приложение, но у меня есть такая проблема:

В основном я пишу этот код:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(
          value: ImgProvider(),
        ), // create the provider of images
        ChangeNotifierProvider.value(
          value: Saved(),
        ), // create the provider of Saved
      ],
      child: MaterialApp(
        title: 'HTrip',
        theme: ThemeData(
          primarySwatch: Colors.green,
          accentColor: Colors.yellowAccent,
        ),
        home: SelectionPages(),
        routes: {
          '/saved'  :   (context) => SavedScreen(),
        }, // define the main page to be displayed
      ),
    );
  }
}

и в SelectionPages (), я написал это:

drawer: Account(),

и в Account () я написал это:

class Account extends StatelessWidget {
  Account();
  @override
  Widget build(BuildContext context) {
    final savedItem = Provider.of<Saved>(context);
    return Drawer(
          child: Column(
            children: <Widget>[
              AppBar(
          title: Text("Account"),
          automaticallyImplyLeading: false,
          centerTitle: true,
        ),
        Divider(),
        ListTile(
                leading: Icon(Icons.sd_card),
                title: Text("Saved"),
                onTap: () {
                  debugPrint("Hello button is clicked");
                  Navigator.of(context).pushReplacementNamed('/saved');
                  },
                // dense: true,
                trailing: Chip(
                  label: Text('${savedItem.savedCount}'),
                  labelStyle: TextStyle(color: Theme.of(context).primaryColor),
                ),
                //  enabled: true,
              )
            ]
          )
    );
  }
}

и в SavedScreen () я написал это:

class SavedScreen extends StatefulWidget {
  //static const routeName = '/Saved';

  @override
  _SavedScreenState createState() => _SavedScreenState();
}

class _SavedScreenState extends State<SavedScreen> {
  @override
  Widget build(BuildContext context) {
    final savedItem = Provider.of<Saved>(context);
    return Scaffold(
      appBar: AppBar(title: Text("Saved")),
      body: Column(
        children: <Widget>[
          Card(
            margin: const EdgeInsets.all(15),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      'Saved item',
                      style: TextStyle(fontSize: 20),
                    ),
                    SizedBox(width: 10),
                    Spacer(), // to take all the empty space available in this place
                    Chip(
                      label: Text('${savedItem.savedCount}'),
                    ),
                    FlatButton(onPressed: () {}, child: Text("See all")),
                  ]),
            ),
          ),
          Expanded(
            child: Card(
              child: ImgSavedGridView(),
            ),
          ),
        ],
      ),
    );
  }
}

Но когда я запускаю приложение и нажимаю «Сохранено» (где я запускаю этот «Navigator.of (context) .pushReplacementNamed ('/ saved');»), я получил следующую ошибку:

════════════════════════════════════════════════════════════════════════════════
I/flutter (27612): Hello button is clicked

════════ Exception caught by gesture ═══════════════════════════════════════════
Could not find a generator for route RouteSettings("/saved", null) in the _WidgetsAppState.
════════════════════════════════════════════════════════════════════════════════

PS: когда я изменил "Navigator.of (context) .pushReplacementNamed ('/ saved');" в "Navigator.of (context) .pushReplacementNamed ('/');". это go на главную страницу без проблем

пожалуйста, помогите мне!

Я здесь для любых разъяснений.

Спасибо

1 Ответ

0 голосов
/ 09 мая 2020

Как видно из нашего обсуждения, вы также используете виджет MaterialApp в SelectionPages, где вы не определяли маршрутизацию, но навигатор ищет маршрутизацию по их.

Просто удалите виджет MaterialApp в SelectionPages, чтобы решить вашу проблему.

...