Перемещение ящика приложения на новую страницу - PullRequest
0 голосов
/ 16 июня 2019

В поисках лучшего способа сделать это, как я могу перейти от ящика приложения к следующей странице, я создал виджет с сохранением состояния в другом файле и импортировал его в main.dart вместо

Navigate.pop(context);

что мне использовать?

Я пытался

Navigator.of(context).push(
    MaterialPageRoute<Null>(builder: (BuildContext context) {
        return new HomePage();

загружает страницу над предыдущей страницей и делает ее запаздывающей.

ниже код.

  return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Center(child: Text('some text')),
      drawer: Drawer(
        // Add a ListView to the drawer. This ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
                image: DecorationImage(image: AssetImage("assets/gold.jpg"),fit: BoxFit.cover)
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer // how do i close the drawer after click?
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );

Я ожидаю, что когда я нажму на ссылку в ящике приложения, я перейду на новую страницу и закрою сам ящик приложения

1 Ответ

0 голосов
/ 17 июня 2019

Если вы ищете способ отредактировать ваши текущие страницы, например, вкладки, а затем переключаться между представлениями без фактического запуска маршрута новой страницы.

Что я обычно делаю, это:

enum Section
{
    GUEST,
    HOME,
    PAGE_1,
    PAGE_2
}

Ваша основная функция сборки:

@override
Widget build(BuildContext context)
{
    Widget body;

    /// You can easily control the section for example inside the initState where you check
    /// if the user logged in, or other related logic
    switch (section)
    {
        /// This is for example a login page since the user not logged in
        case Section.GUEST:
            break;

        /// Display the home section, simply by
        case Section.HOME:
            body = HomeSection();
            break;

        case Section.PAGE_1:
            body = Page1Section();
            break;

        case Section.PAGE_2:
            body = Page2Section();
            break;
    }

    return Scaffold(
        body: Container(
            child: body,
        ),
        /// Display the drawer for logged in users only
        drawer: section != Section.GUEST ? Drawer(
            // Your drawer
        ) : null,
    );
}

Это даже сохранит состояние между этими разделами, и вы быстро перемещаетесь между ними.

Перегружая ящик, вы делаетеэто правильно.Вы просто делаете это с помощью навигатора в контексте.Просто убедитесь, что у вас есть правильный контекст. (а не распространяемый)

И, конечно, изменить раздел просто:

setState(() => section = Section.HOME);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...