2021年7月24日 星期六

[又重學flutter]使用InheritedModel(所有頁面共用資料,類似vuex)

 

//marin.dart
import 'package:flutter/material.dart';
import 'page2.dart';
void main() {
  runApp(GlobalData(
    child: MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (BuildContext context) => HomePage(),
        '/page2': (BuildContext context) => Page2(),
      },
    ),
  ));
}

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('image')),
        body: Column(
          children: [
            GestureDetector(
              onTap: () {
                GlobalData.of(context).title = 'new Title';
                Navigator.of(context).pushNamed('/page2');
              },
              child: Text('page2'),
            )
          ],
        ));
  }
}

class GlobalData extends InheritedModel {
  GlobalData({
    this.title,
    Widget? child,
  }) : super(child: child!);

  String? title;

  static GlobalData of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<GlobalData>()!;
  }

  
  bool updateShouldNotify(GlobalData old) => title != old.title;

  
  bool updateShouldNotifyDependent(GlobalData oldWidget, Set dependencies) {
    if (dependencies.contains('title') && oldWidget.title != title) {
      return true;
    }
    return false;
  }
}

//page2.dart
import 'package:flutter/material.dart';
import 'main.dart';

class Page2 extends StatelessWidget {
  Page2();
  
  Widget build(BuildContext context) {
    GlobalData g = GlobalData.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('${g.title}'),
      ),
    );
  }
}





























呈現效果 https://github.com/fenturechance/flutterPractice2021/tree/847d2585e9c48ecd5d8e38238dbc8ea2b7329b8a















沒有留言:

張貼留言