Search code examples
flutterflutter-providermobile-developmentstate-managementflutter-state

How to set data in an inherited widget from a another widget?


So inherited widget is useful for passing data down the tree, but how do I set that data in the first place if inherited widgets are immutable? I'm trying to set a phone number for OTP auth and then display that number on another screen. Provider is kind of advanced for me at the moment, how do I approach this? thank you


Solution

  • You have to rebuild somewhere your InheritedWidget. You can use any stage management for it, for example you can use StatefulWidget:

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    
    class MyInheritedWidget extends InheritedWidget {
     final int counter;
    
     MyInheritedWidget({Key key, this.counter, Widget child})
         : super(key: key, child: child);
    
     @override
     bool updateShouldNotify(MyInheritedWidget oldWidget) {
       return oldWidget.counter != counter;
     }
    
     static MyInheritedWidget of(BuildContext context) {
       return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
     }
    }
    
    void main() {
     runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
       return MaterialApp(
         home: Home(),
       );
     }
    }
    
    class Home extends StatefulWidget {
     @override
     _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
     int _counter = 0;
    
     @override
     Widget build(BuildContext context) {
       return Scaffold(
         body: Center(
           child: MyInheritedWidget(counter: _counter, child: CounterWidget()),
         ),
         floatingActionButton: FloatingActionButton(
           onPressed: () {
             setState(() {
               _counter++;
             });
           },
         ),
       );
     }
    }
    
    class CounterWidget extends StatelessWidget {
     @override
     Widget build(BuildContext context) {
       return Text("${MyInheritedWidget.of(context).counter}",
           style: TextStyle(fontSize: 100));
     }
    }