0

Всем привет. Начал изучать flutter и хочу сделать следующее: запускаю приложение, вижу главный экран. Свайпом вправо выдвигаю панель drawer в которой у меня есть некоторые меню. При выборе меню нужно что бы в текущем "Activity" (Если это так можно назвать) заменялись данные внутри тэга "body". Сейчас же у меня открывается новый "Activity" в котором расположена кнопка. Как реализовать что бы менялся только тэг "body"?

main.dart:

import 'package:flutter/material.dart';
import 'package:mg_by/App/mainScreen.dart';

void main() {
  runApp(MaterialApp(
    title: 'Приложение',
    home: MainScreen(),
  ));
}

mainScreen.dart:

import 'package:flutter/material.dart';
import 'package:mg_by/App/Second.dart';

class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: new AppBar(
        leading: new Icon(Icons.menu),
        title: new Text("Приложение"),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.shopping_cart),
            onPressed: () {},
          ),
          new IconButton(
            icon: new Icon(Icons.monetization_on),
            onPressed: () {},
          )
        ],
      ),
      body: new Container(
        color: Colors.red,
      ),
      // Этот виджет представляет собой DrawerLayout в Android, который выезжает из левой части Activity для отображения навигационных ссылок приложения.
      drawer: new Drawer(
        child: new ListView(
          children: <Widget>[
            new DrawerHeader(
              child: new Text("Drawer Header"),
              decoration: new BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Второй экран'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => SecondScreen()),
                );
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}

Second.dart:

import 'package:flutter/material.dart';

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
      Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Вернуться назад.'),
        ),
      ),
    );
  }
}

1 ответ 1

1

У тебя StatelessWidget, а то что ты хочешь получить возможно только в Statefull. Ну это если я правильно понял...Я сам флаттер изучаю третью неделю, так что, возможно ответ и неверный.

import 'package:flutter/material.dart';

class MainScreen extends StatefulWidget {
  _MainScreen createState() => _MainScreen();
}

class _MainScreen extends State<MainScreen> {
  var page = 'main';

  _getMainScreen(page) {
    if (page == 'main') {
      return new Container(
        color: Colors.red,
      );
    } else {
      return new Container(
        color: Colors.red,
        child: Center(
          child: RaisedButton(
            onPressed: () {
              setState(() {
                this.page = 'main';
              });
            },
            child: Text('Вернуться назад.'),
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: new AppBar(
        leading: new Icon(Icons.menu),
        title: new Text("Приложение"),
        actions: <Widget>[
          new IconButton(
            icon: new Icon(Icons.shopping_cart),
            onPressed: () {},
          ),
          new IconButton(
            icon: new Icon(Icons.monetization_on),
            onPressed: () {},
          )
        ],
      ),
      body: _getMainScreen(page),

      // Этот виджет представляет собой DrawerLayout в Android, который выезжает из левой части Activity для отображения навигационных ссылок приложения.
      drawer: new Drawer(
        child: new ListView(
          children: <Widget>[
            new DrawerHeader(
              child: new Text("Drawer Header"),
              decoration: new BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Второй экран'),
              onTap: () {
                setState(() {
                  page = 'second';
                });
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                setState(() {
                  page = 'main';
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}
1
  • Это действительно заработало, спасибо большое
    – Leksor
    2 ноя 2018 в 12:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.