Flutter change scaffold body from side drawer

I am trying to change the content of the Scaffold body from the side drawer in Flutter. I am using different files to store the side navigation bar and new body contents.

I have created a separate file with a class NavigationController, which contains a static variable for the widget to be displayed in the body of the scaffold.

I am using different files to have better organisation.

Thanks in advance and any suggestions are highly appreciated.

The variable is getting updated as I have tested using the print function.

Also I am able to change the contents of the screen after clicking the button in the side navigation bar if i press a button on the page which does a set state.

So it seems that the set state I am executing when pressing the button in the side navigation bar is not refreshing the main page.

Main App:

import 'package:flutter/material.dart';
import 'package:playground/sidenav.dart';
import 'package:playground/pagecontroller.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: const SideNav(),
      appBar: AppBar(),
      body: NavigationController.currentPage,
    );
  }
}

Navigation controller:

import 'package:flutter/material.dart';

class NavigationController {
  static Widget currentPage = const Text("Hello World");
}

Side Drawer Widget:

import 'package:flutter/material.dart';
import 'package:playground/pagecontroller.dart';
import 'package:playground/newbody.dart';

class SideNav extends StatefulWidget {
  const SideNav({super.key});

  @override
  State<SideNav> createState() => _SideNavState();
}

class _SideNavState extends State<SideNav> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(children: <Widget>[
      ListTile(
          title: const Text('Page 1'),
          onTap: () {
            setState(() {
              NavigationController.currentPage = const NewBody();
              Navigator.pop(context);
            });
          })
    ]));
  }
}

>Solution :

hope you are fine.

setState is refreshing `SideNav` and not the main widget.

You have to use a better solution, try to read about state management and providers.

recommend to use Flutter provider or Flutter cubit
you can achieve this by creating a home page with a listener -> watching any change that comes from the provider and reloading the widget with a new one.

Leave a Reply