I have no Idea anymore.
I am using Mobx for really simple State Management.
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:jw_helper/state/globalState.dart';
class Router extends StatelessWidget {
const Router({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _globalState = GlobalState();
return Column(
children: <Widget>[
Container(
child: Observer(
builder: (_) => Text(_globalState?.currentIndex?.toString()),
),
),
MaterialButton(
onPressed: () {
_globalState.setCurrentIndex(1);
},
child: Text("Press me"),
),
],
);
}
}
When i mutate the state in this widget the value updates. When i mutate the same Observable in another Widget the Observer is not rebuilding.
Only the observer in the same Widget where the State is mutated is updated.
My Mobx Code:
import 'package:mobx/mobx.dart';
// Include generated file
part 'globalState.g.dart';
// This is the class used by rest of your codebase
class GlobalState = _GlobalState with _$GlobalState;
// The store-class
abstract class _GlobalState with Store {
@observable
int currentIndex = 0;
@action
void setCurrentIndex(index) {
currentIndex = index;
print(currentIndex);
}
}
Small note: The Print Statement is always fired
Maybe someone knows how to fix this. Thank you ;)
The Problem was solved with Help from a Discord Mobx Channel Member.
The solution was to wrap the whole App in a provider Widget.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
------------------------------------------------
return Provider<GlobalState>(
create: (context) => GlobalState(),
------------------------------------------------
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: SplashScreen(),
),
);
}
}
In the Widgets consuming the Mobx Class i did:
class Router extends StatelessWidget {
const Router({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final _globalState = Provider.of<GlobalState>(context);
return Column(
children: <Widget>[
Container(.....
Hopefully this helps somebody to get up and running ;)