Home > database >  passing state in flutter with no state management tools
passing state in flutter with no state management tools

Time:03-10

I am going through a flutter course on Udemy: Complete Flutter App Development Bootcamp with Dart I am in the provider package chapter. as an intro to state management, we have the following example code to illustrate how effort consuming it is to pass state in between classes and widgets without the use of a state management tool. the code is as follows:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final String data = 'this is the test data';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: MyText(),
          ),
          body: Level1(data),
        ),
      );
  }
}

class Level1 extends StatelessWidget {
  final String data;
  Level1(this.data);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Level2(data),
    );
  }
}

class Level2 extends StatelessWidget {
  final String data;
  Level2(this.data);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        MyTextField(),
        Level3(data),
      ],
    );
  }
}

class Level3 extends StatelessWidget {
  final String datta;

  Level3(this.datta);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Text('data')
    );
  }
}

The point that the tutor is trying to make here is:

"with no state management tools, if we want the first variable data mentioned in MyApp class to be used also in Level3 class we will need to drill through all other classes : Level1 and Level2"

I am not sure why she isn't calling the Level3 constructor immediately in MyApp class? why is this drilling through classes even an option here? I understand that it is not optimal for coding and I agree, but we can just call Level3 constructor directly! can't we? can someone provide more explanation?

CodePudding user response:

Well that's a bad way of teaching state management in Flutter!

Flutter's built-in state management is great already. What you need is to look at the InheritedModel that allows you to inherit state all the way down the widget chain and to even pick an aspect of the state that you want to inherit.

Here is a video that explains how you can use InheritedModel in Flutter: https://www.youtube.com/watch?v=0vl35jtpsfs&list=PL6yRaaP0WPkUf-ff1OX99DVSL1cynLHxO&index=4&ab_channel=VandadNahavandipoor

  • Related