我举了一个简单的示例来理解如何在Flutter中使用带有提供程序模式的Stream。
我不知道在这种情况下如何更改流值? -当我单击“添加”图标时,该值将被添加,计数值将增加(例如Sink.add)
请帮助我了解将流与提供程序配合使用。
非常感谢!
屏幕:
这是我的代码:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
// Main app and Pages for Tab Layout
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MultiProvider(
providers: [
StreamProvider(
create: (_) => EventProvider().intStream(), initialData: 0),
],
child: DefaultTabController(
length: 1,
child: DefaultTabController(
length: 1,
child: Scaffold(
appBar: AppBar(
title: Text("Provider Demo"),
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.add)),
],
),
),
body: TabBarView(
children: [
MyEventPage(),
],
),
),
))));
}
}
// Event page (counting)
class MyEventPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var _value = Provider.of<int>(context);
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('StreamProvider Example'),
SizedBox(height: 50),
Text('${_value.toString()}',
style: Theme.of(context).textTheme.display1)
],
)),
Align(
alignment: Alignment.bottomRight,
child: RaisedButton(
onPressed: () {
EventProvider().add();
},
child: Icon(Icons.add),
),
)
],
));
}
}
// User List Page
// EventProvider (Stream)
class EventProvider {
StreamController<int> sc = StreamController();
int count = 0;
Stream<int> intStream() {
// return Stream<int>.periodic(interval, (int _count) => _count++);
return sc.stream;
}
add () {
count++;
sc.sink.add;
}
}
答案 0 :(得分:0)
我只想分享我的理解。
我需要创建单例EventProvider实例。
对于像我这样的人,这是我更改的代码:
const cheerio = require('cheerio');
const sampleHTML = `
<div class="row">
<div class="col-12"></div>
<div class="col-xl-4"></div>
<div class="col-xl-4"></div>
<div class="col-xl-4"></div>
<div class="col-12"></div>
<div class="col-12"></div>
<div class="col-12"></div>
</div>
`;
let $ = cheerio.load(sampleHTML);
let divs = $(".row > div");
let state = "looking-col-12";
let cnt = 0;
divs.each((i, div) => {
let item = $(div);
switch (state) {
case "looking-col-12":
if (item.hasClass("col-12")) {
state = "lookingFirst-xl-4";
}
break;
case "lookingFirst-xl-4":
if (item.hasClass("col-xl-4")) {
state = "counting-xl-4";
cnt = 1;
}
break;
case "counting-xl-4":
if (item.hasClass("col-xl-4")) {
++cnt;
} else {
state = "done";
}
break;
default:
break;
}
});
console.log(cnt);