Flutter-自定义通知

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('监听'),
        ),
        body: NotificationRoute(),
      ),
    );
  }
}

class NotificationRoute extends StatefulWidget {
  @override
  _NotificationRouteState createState() => _NotificationRouteState();
}

class _NotificationRouteState extends State {
  
  String _msg = '';
  
  @override
  Widget build(BuildContext context) {
    return NotificationListener(
        onNotification: (notification) {
          setState(() {
            _msg += notification.msg + '  ';
          });
        }, 
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 通过Builder来构建RaisedButton,来获得按钮位置的context
              Builder(
                  builder: (context) {
                    return RaisedButton(
                      onPressed: () => MyNotification('hi').dispatch(context),
                      child: Text('send notification'),
                    );
                  }
              ),
              Text(_msg),
            ],
          ),
        ),
    );
  }
}

class MyNotification extends Notification {
  MyNotification(this.msg);
  
  final String msg;
}

你可能感兴趣的:(Flutter-自定义通知)