关于python:Flutter跨组件传递事件

45次阅读

共计 1848 个字符,预计需要花费 5 分钟才能阅读完成。


步骤

1. 引入第三方库

pubspec.yaml 引入 event_bus: ^1.1.1

2. 定义在组件之间传递的对象

class UserInfo {
  String nickname;
  int level;
    
  UserInfo(this.nickname, this.level);
}

3. 创立全局的 EventBus 对象

final eventBus = EventBus();

4. 在某个 widget 收回事件

FlatButton(child: Text("Testbutton", style: TextStyle(color: Colors.white)),
              color: Colors.orange, // 按钮的色彩

              onPressed: () {final info = UserInfo("why", 18);
                eventBus.fire(info);
              },
            ),

5. 在另一个 widget 监听事件

  @override
  void initState() {super.initState();

    eventBus.on<UserInfo>().listen((data) {setState(() {message = "${data.nickname}-${data.level}";
      });
    });
  }

残缺代码

import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

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

class UserInfo {
  String nickname;
  int level;

  UserInfo(this.nickname, this.level);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue,),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {final eventBus = EventBus();

  String message = "Hello Coderwhy";

  @override
  void initState() {super.initState();

    eventBus.on<UserInfo>().listen((data) {setState(() {message = "${data.nickname}-${data.level}";
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              message,
              style: Theme.of(context).textTheme.headline4,
            ),
            FlatButton(child: Text("Testbutton", style: TextStyle(color: Colors.white)),
              color: Colors.orange, // 按钮的色彩

              onPressed: () {final info = UserInfo("why", 18);
                eventBus.fire(info);
              },
            ),
          ],
        ),
      ),
    );
  }
}

参考

Flutter 写的 app, 须要源码能够私信~~

  • 简繁火星字体转换
  • 哄女友神器
  • 号码测吉凶
  • 电视节目直播表

最好的笔记软件

https://www.wolai.com/signup?…

正文完
 0