gpt4 book ai didi

flutter - 将 StreamBuilder 转换为 StreamProvider

转载 作者:行者123 更新时间:2023-12-05 04:31:09 29 4
gpt4 key购买 nike

我有一个像这样的 StreamBuilder:

StreamBuilder<List<AuthInfo>>(
stream: myDatabase.authInfosDao.watch(),
builder: (context, snapshot) => (snapshot.data?.length ?? 0) > 0
? Home()
: Auth()),

我想将它重做成一个 Stream Provider,这就是发生的事情:

StreamProvider<List<AuthInfo>>.value(
value: myDatabase.authInfosDao.watch(),
initialData: [],
builder: (BuildContext context, AsyncSnapshop snapshot)...

我不知道如何使用“值”中的数据来加载所需的页面,因为 StreamProvider 中没有快照

最佳答案

每次新数据到达流时,StreamProvider 都会重建小部件。它的功能类似于 ChangeNotificationProvider,它不会生成新的更改放置更新数据,提供程序正在监听。

dependencies:
flutter:
sdk: flutter
provider: ^6.0.2

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

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

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return
StreamProvider<ModelObject>(
initialData: ModelObject(value:0),
create:(_)=>createStream(),
child: MaterialApp(
home: Test_StreamProviderWidget(),
));

}
}

class ModelObject{

ModelObject({this.value});
int ? value;
}
Stream<ModelObject> createStream(){
return
Stream<ModelObject>.periodic( Duration(seconds:1), (currentPeriodicValue)=>ModelObject(value:currentPeriodicValue+1)).take(10000);
}

class Test_StreamProviderWidget extends StatefulWidget {
Test_StreamProviderWidget({Key? key}) : super(key: key);

@override
State<Test_StreamProviderWidget> createState() => _Test_StreamProviderWidgetState();
}

class _Test_StreamProviderWidgetState extends State<Test_StreamProviderWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title:Text("stream provider")),body:
Consumer<ModelObject>(
builder:(context, model, child) {
return
Center(child:Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [

Text('${model.value.toString()}',style: Theme.of(context).textTheme.headline2,)

],));

},

)
)
;
}
}

关于flutter - 将 StreamBuilder 转换为 StreamProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71883912/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com