Skip to content

Instantly share code, notes, and snippets.

@yenru
Last active May 16, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yenru/7c35a6e8fc568358276801e8127cf1f5 to your computer and use it in GitHub Desktop.
Save yenru/7c35a6e8fc568358276801e8127cf1f5 to your computer and use it in GitHub Desktop.
將計數器Sample的StatefulWidget修改成只有數字的部份。方法三:使用StreamController與Provider注入。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
//建立StreamController,並宣告注入值的型態
final _controller = StreamController<int>();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: StreamProvider.value(
initialData: 0, //設定注入的初始值
stream: _controller.stream,
child: MyHomePage(
title: 'Flutter Demo Home Page', controller: _controller)),
);
}
@override
void dispose() {
//StreamController寫成區域變數要close()
_controller.close();
super.dispose();
}
}
class MyHomePage extends StatelessWidget {
final String title;
final StreamController controller;
MyHomePage({Key key, this.title, this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
//取得上層注入的值
int _counter = Provider.of<int>(context);
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
CounterField(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
controller.add(++_counter); //更新注入的值
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class CounterField extends StatefulWidget {
@override
_CounterFieldState createState() => _CounterFieldState();
}
class _CounterFieldState extends State<CounterField> {
@override
Widget build(BuildContext context) {
//取得上層注入的值
int _counter = Provider.of<int>(context);
return Text(
'$_counter', //顯示注入的值
style: Theme.of(context).textTheme.display1,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment